Tasks and modules

Tip

We recommend to use the Sandbox to play around with this example.

Tip

All the files from this section are in tasks-and-modules.zip.

In Introduction, we mentioned that a playbook is a list of plays. A play has one or more tasks. A task is the combination of

  • metadata (for example, the name of the task),

  • module and its arguments, and

  • additional instructions (for example, for repeat the module with different values).

So far, the only module that we use was ansible.builtin.debug that is part of the default library, a large collection of modules that is provided with Ansible. Additional module are available from Ansible Galaxy.

Playbook

playbook.yml
- name: Creating files
  hosts:
    - web
  tasks:
    - name: Create a directory if it does not exist
      ansible.builtin.file:
        path: /tmp/example
        state: directory
        owner: ansible
        group: ansible
        mode: 'u=rwx,g=rx,o=rx'
    - name: Ensure line is present in file
      ansible.builtin.lineinfile:
        path: /tmp/example/answer.txt
        line: '42'
        state: present
        create: true
        owner: ansible
        group: ansible
        mode: 'u=rw,g=r,o=r'

The above playbook has a single play with two tasks:

  1. creates a directory.

  2. insert a line in a file.

Running

cd task-and-modules
ansible-playbook \
--ask-vault-pass \
-i inventories/production.yml \
--extra-vars @vault/production \
playbook.yaml

Note

The password for the vault used in the example is 123. You must use a strong passwords, for example, a minimum of 8 randomly generated characters.

returns

PLAY [Creating files] **********************************************************

TASK [Gathering Facts] *********************************************************
ok: [managed_node_01]

TASK [Create a directory if it does not exist] *********************************
ok: [managed_node_01]

TASK [Ensure line is present in file] ******************************************
ok: [managed_node_01]

PLAY RECAP *********************************************************************
managed_node_01            : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0