Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Automation and Troubleshooting

Configuration Management and Idempotence with Ansible

Manage many Linux servers consistently with Ansible: inventory, ad-hoc commands, playbooks, modules, handlers, variables, templates, check mode and why idempotence is the core idea.

Shell scripts are fine for one machine. When you must configure twenty servers identically, rebuild one from scratch after a failure, or prove what a server's configuration should be, you want configuration management: you describe the desired state in files, and a tool makes machines match it. Ansible is the most popular such tool on Linux because it needs no agent on the servers; it connects over SSH (see Remote Access with SSH) and runs small modules.

Ansible itself cannot run on this site. Playbooks are shown as read-only code, and the Python stand-ins demonstrate the idea that makes the whole approach work: idempotent operations that check the current state and change only what differs.

Desired state beats a list of commands

A script says "append this line to the file". Run it twice and the line appears twice. A desired-state description says "this line must be present in the file". Run it twice and the second run changes nothing. That property, idempotence, makes configuration safe to re-run on a schedule, which also cures drift (servers slowly differing because of manual changes).

flowchart LR
    D["desired state<br/>(playbook in Git)"] --> C["compare with<br/>actual state"]
    C -- "already correct" --> O["ok, no change"]
    C -- "differs" --> A["apply change"]
    A --> R["report: changed"]

Every Ansible module follows this check-then-act cycle.

Inventory

The inventory lists the machines and groups them.

INI
# inventory.ini
[web]
web01.example.org
web02.example.org ansible_port=2222

[db]
db01.example.org

[prod:children]
web
db

[all:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3

Ad-hoc commands run one module on a group, ideal for quick facts and emergencies:

Terminal
ansible all -i inventory.ini -m ping
ansible web -i inventory.ini -a "uptime"
ansible web -i inventory.ini -b -m apt -a "name=nginx state=present update_cache=yes"
ansible db -i inventory.ini -b -m service -a "name=postgresql state=restarted"

-b means "become" (use sudo). Key-based SSH, a sudo rule for the deploy user, and a Python 3 interpreter on the target are the only prerequisites.

A playbook

A playbook is YAML: a list of plays, each applying tasks (module calls) to a group of hosts.

YAML
# web.yml
- name: Configure web servers
  hosts: web
  become: true
  vars:
    http_port: 80
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Deploy site configuration
      ansible.builtin.template:
        src: site.conf.j2
        dest: /etc/nginx/conf.d/site.conf
        owner: root
        group: root
        mode: "0644"
        validate: "nginx -t -c /etc/nginx/nginx.conf"
      notify: Reload nginx

    - name: Ensure sshd forbids root login
      ansible.builtin.lineinfile:
        path: /etc/ssh/sshd_config.d/10-hardening.conf
        line: "PermitRootLogin no"
        create: true
        mode: "0644"
      notify: Reload sshd

    - name: Ensure nginx is enabled and running
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

  handlers:
    - name: Reload nginx
      ansible.builtin.service: {name: nginx, state: reloaded}
    - name: Reload sshd
      ansible.builtin.service: {name: ssh, state: reloaded}

Run it:

Terminal
ansible-playbook -i inventory.ini web.yml --check --diff    # dry run, show diffs
ansible-playbook -i inventory.ini web.yml                   # apply
ansible-playbook -i inventory.ini web.yml --limit web01.example.org
ansible-playbook -i inventory.ini web.yml --tags ssh

The output of a run ends with a recap per host: ok, changed, failed, unreachable, skipped. The healthy second run of a converged server shows changed=0.

Key ideas:

  • Modules, not shell. apt, dnf, service, user, file, copy, template, lineinfile, cron, firewalld, ufw, sysctl, mount know how to check state. The generic command and shell modules are not idempotent unless you add creates: or changed_when:.
  • Handlers run only when a task reported a change, and once at the end of the play: the nginx reload happens only if the config really changed.
  • Templates use Jinja2 ({{ http_port }}) to produce per-host files from variables.
  • Variables and facts. Values come from the inventory, group_vars/, host_vars/ and discovered facts (ansible_distribution, ansible_memtotal_mb).
  • Check mode (--check) predicts changes without applying them, and --diff shows file differences.
  • Roles package tasks, templates and defaults for reuse (ansible-galaxy init myrole).
  • Secrets go in Ansible Vault (ansible-vault encrypt_string) or an external secret manager, never in plain text in Git.
Python Idempotent 'lineinfile' versus a naive append

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mini Ansible: a convergence loop

Python Stand-in: plan, check mode and apply

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Practical advice

  1. Keep playbooks, inventories and templates in Git, and review changes like code.
  2. Run ansible-lint and --check --diff in your review pipeline.
  3. Start with the boring tasks: users, SSH keys, packages, firewall rules, sysctl, time sync, monitoring agents.
  4. Prefer pull from Git plus scheduled runs (or a controller such as AWX or Semaphore) once teams grow.
  5. Alternatives exist: Puppet and Chef (agent-based, strong at continuous convergence), Salt, and for cloud resources Terraform or OpenTofu. Immutable approaches (building a fresh image or container per change) reduce drift even further. The ideas transfer between tools.
  6. Never edit a managed server by hand. If you do in an emergency, put the same change in the playbook afterwards.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does idempotent mean for a configuration task?

    Modules check the current state and act only when it differs from the desired state.
  2. 2. Why might the shell module break idempotence?

    Purpose-built modules compare state; raw commands do not.
  3. 3. When does a handler such as Reload nginx run?

    Handlers avoid needless restarts and group several notifications into one run.
  4. 4. Which flags preview what a playbook would change?

    --check does a dry run and --diff shows file differences.

Summary

  • Configuration management describes desired state; idempotent modules make repeated runs safe and fix drift.
  • Ansible is agentless: an inventory of hosts, ad-hoc commands, and YAML playbooks of module calls over SSH.
  • Use real modules, handlers for restarts, Jinja2 templates, variables and facts, and Vault for secrets.
  • Preview with --check --diff, keep everything in Git, lint it, and avoid manual edits on managed servers.

Next: A Troubleshooting Playbook