Ansible Tips
Some useful Ansible tips for quick reference.
Install a local ansible role
The following installs the role in the current directory.
ansible-galaxy install "git+file://$(realpath .)"
Replace .
with other relative or absolute dir to install role located at other directory.
Order of operations for a play
- Fact gathering
- Variable loading
- The pre_tasks execution
- Handlers notified from the pre_tasks execution
- Roles execution (Each role listed in roles will execute in turn. Any role dependencies defined in the roles meta/main.yml will be run first, subject to tag filtering and conditionals.)
- Tasks execution
- Handlers notified from roles or tasks execution
- The post_tasks execution
- Handlers notified from the post_tasks execution
---
- hosts: localhost
gather_facts: false
vars:
- a_var: derp
pre_tasks:
- name: pretask
debug:
msg: "a pre task"
changed_when: true
notify: say hi
roles:
- role: simple
derp: newval
tasks:
- name: task
debug:
msg: "a task"
changed_when: true
notify: say hi
post_tasks:
- name: posttask
debug:
msg: "a post task"
changed_when: true
notify: say hi
Ref: Order of operations - Mastering Ansible - Third Edition
Run task locally
-
delegate_to: localhost
directivetasks: - name: take out of load balancer pool command: /usr/bin/take_out_of_pool delegate_to: 127.0.0.1
-
local_action
moduletasks: - name: take out of load balancer pool local_action: command /usr/bin/take_out_of_pool
This one is basically the same as
delegate_to: localhost
, but deprecated for the reason:To increase readability and match the style of typical ansible tasks, use delegate_to: localhost to replicate the functionality of local_action.
And here is the output from
ansible-lint
iflocal_action
is used:[504] Do not use 'local_action', use 'delegate_to: localhost'
-
connection: local
directive--- - hosts: 127.0.0.1 connection: local
connection: local
runs the entire play locally.Note: If you set the connection to local and there is no
ansible_python_interpreter
set, modules will run under/usr/bin/python
and not under ``. Be sure to setansible_python_interpreter: ""
inhost_vars/localhost.yml
, for example. You can avoid this issue by usinglocal_action
ordelegate_to: localhost
instead.In addition, the connection directive can be overridden on commnad line:
ansible-playbook -c local ...
Debug inventory
Inventory can be specified with env var ANSIBLE_INVENTORY
, or on command line via -i <file>
, or in ansible.cfg
:
[defaults]
inventory = path/to/inventory
To list hosts matched by a group or graph an inventory, use the following methods:
-
ansible --list-hosts all
Replace
all
with the group you want to list. -
ansible-inventory --graph
-
Use variable
play_hosts
andinventory_hostname
in a play.