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

  1. Fact gathering
  2. Variable loading
  3. The pre_tasks execution
  4. Handlers notified from the pre_tasks execution
  5. 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.)
  6. Tasks execution
  7. Handlers notified from roles or tasks execution
  8. The post_tasks execution
  9. Handlers notified from the post_tasks execution
- hosts: localhost
  gather_facts: false

    - a_var: derp

    - name: pretask
        msg: "a pre task"
      changed_when: true
      notify: say hi

    - role: simple
      derp: newval

    - name: task
        msg: "a task"
      changed_when: true
      notify: say hi

    - name: posttask
        msg: "a post task"
      changed_when: true
      notify: say hi

Ref: Order of operations - Mastering Ansible - Third Edition

Run task locally

  1. delegate_to: localhost directive

    - name: take out of load balancer pool
      command: /usr/bin/take_out_of_pool 
  2. local_action module

    - 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 if local_action is used:

    [504] Do not use 'local_action', use 'delegate_to: localhost'

  3. connection: local directive

    - hosts:
      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 set ansible_python_interpreter: "" in host_vars/localhost.yml, for example. You can avoid this issue by using local_action or delegate_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:

inventory = path/to/inventory

To list hosts matched by a group or graph an inventory, use the following methods:

  1. ansible --list-hosts all

    Replace all with the group you want to list.

  2. ansible-inventory --graph

  3. Use variable play_hosts and inventory_hostname in a play.