>_ IzzyLab

Hands-on task

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

Ansible: idempotent line in a file

medium~12 min

The config /etc/app/hosts.conf already has entries. Write a playbook /root/line.yml that ensures the presence of the line db.local 127.0.0.1 in it (the lineinfile module — adds it if the line is missing and won't duplicate it on a repeat run), leaving the other lines alone. Run it. The playbook must work whatever the file contains: add the line if it's missing, leave other entries alone, and change nothing on a second run.

What you'll practise:
  • ansible
  • lineinfile
  • idempotency
  • editing configs
  • iac

Topic breakdown

The lineinfile module ensures that a given line is present in a text file: if it's missing — it adds it, if it's there — it leaves it as is. This is the core of idempotency in the "infrastructure as code" approach: no matter how many times you run the playbook, the result is the same and no duplicates appear. The module is given the target file and the line itself, and the create parameter creates the file if it doesn't exist yet — there's no need to check for repeats manually, the module does it itself.

What's checked

  1. the playbook adds the line
  2. db.local 127.0.0.1 appears exactly once
  3. the other config lines are intact
  4. a second run changes nothing and adds no duplicates

What it looks like