Inventory and Playbooks

In ansible, the invetory cointains the list of all the available servers that ansible can reach and manage by sending commands to execute.

Ansible has a search order to find available inventories and configuration:

  • First is checks in $pwd/ansible.cfg
  • Then checks in $HOME/ansible.cfg
  • Then finally checks in /etc/ansible/ansible.cfg
  • When the inventory is filled in you can check your list with: ansible –list-hosts all
  • It is possible to generate a dynamic inventory from a shell script: ansible group1 -i dynamic_inv.sh –list

Playbooks are yaml files allowing to import other playbooks and run tasks:

In important point is to know and understand the list of available module (one module is one task called):

By default tasks are run synchronously but it is possible to run then asynchronously

If you need to run with elevated users:

  • Add -K parameter in the command line for the password prompt of the elevated user
  • Add those line in the code
    • become: ‘true’
    • become_user: ‘root’

To check a playbook simply add the parameter –check into the command line

To run a specific task, tag the task and run the command line ansible-playbook with the parameter –tags TAG_NAME

Request data by prompt:

vars_prompt:

  • name: “variable”
    prompt: “Please enter data:”
  • Can be combined with when: variable == ‘yes’ for conditional tasks execution

To run tasks asynchronous:
Use the keyword: async: XX (where XX is a measure in seconds)

When using async, you can specify the poll keyword that will check when to check the if the async tasks is finished: poll: XX (where XX is a measure in seconds)
tasks:
– name: Sleep
command: sleep 65
async: 55
poll: 10
The task has 55 seconds to finish and every 10 seconds, ansible will check if the tasks is completed.
Ansible will kill the task and put it in fail.

If poll is equal to 0, ansible will not check and will wait for the task to finish or to pass the async limit period.

Here is a small playbook example:

  • It runs as root
  • Will use the ansible apt module if the os family is Debian
  • Will use the ansible yum module if the os family is RedHat
  • Will use the ansible shell module to run the zypper update if the os family is Suse