>_ IzzyLab

Hands-on task

This task is step 6 of the course “Terraform and Ansible”

Ansible: create users with a loop

medium~12 min

Write a playbook /root/users.yml (target localhost, local connection) that uses a loop to create three users: alice, bob, carol. Run it. The playbook must create the users on a machine where they don't exist yet, and a second run must change nothing.

What you'll practise:
  • ansible
  • user module
  • loop
  • ansible-playbook
  • jinja2

Topic breakdown

Ansible describes the desired state of the system declaratively in a YAML playbook, and modules do the actual work — the user module handles accounts. To avoid duplicating the same task for each user, you attach a loop to it: the task repeats for each element of a list, and the current element is available through the item variable, substituted with Jinja2 syntax. The playbook is targeted at the local machine (connection: local), and creating users requires elevated privileges (become).

What's checked

  1. the playbook creates the users from scratch
  2. users alice, bob, carol are created
  3. the users are created in a loop
  4. a second run changes nothing (changed=0)

What it looks like