27.3. Automating Hosts with Ansible

Shell automation manages one machine well; a fleet needs a different shape. A configuration management system stores the intended state of many hosts in code, computes what differs on each of them, and applies only the differences - repeatedly, safely, and without an agent process resident on every host. The approaches available on Debian 13 differ in where the intelligence lives:

Approach Transport and agent Model On Debian 13
Shell over SSH one script, your keys imperative: you write every step already installed
Ansible (ansible-core) SSH from a control node, no resident agent declarative playbooks, push packaged, 2.19.11
Puppet agent on each host, pulls from a master declarative manifests with a DSL packaged (puppet)
Salt minion agents, or salt-ssh agentless declarative states, push or pull not in the trixie archive; packages come from Salt's own repository

Ansible fits the scale this book works at - a handful to a few hundred hosts, already administered over SSH - because it reuses the SSH trust this chapter has already built and adds no daemon. Puppet and Salt reward larger estates with richer client reporting and continuous convergence; choosing between them is a fleet-level decision rather than a per-host one. The rest of this section is Ansible, from the control node's installation to a failed rollout and its recovery.

27.3.1. Control Node Installation, Inventory, and SSH Access

Install Ansible on the control node. The ansible-core package carries the engine, the core modules, and the CLI; the larger ansible package adds the community collection bundle, which this chapter does not need:

$ sudo apt install ansible-core
Reading package lists...
Building dependency tree...
Reading state information...
ansible-core is already the newest version (2.19.11-0+deb13u1).
Summary:
  Upgrading: 0, Installing: 0, Removing: 0, Not Upgrading: 66

Check what you have - run from the workspace root, before the Ansible project directory exists:

$ ansible --version
ansible [core 2.19.11]
  config file = None
  configured module search path = ['/home/john/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  ansible collection location = /home/john/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.13.5 (main, May  5 2026, 21:05:52) [GCC 14.2.0] (/usr/bin/python3)
  jinja version = 3.1.6
  pyyaml version = 6.0.2 (with libyaml v0.2.5)

config file = None says no configuration applies yet; once commands run from a directory containing ansible.cfg, that file is picked up automatically.

Ansible is only as trustworthy as the SSH it rides on, so establish both directions of trust before the first playbook. On the control node, as john, create a dedicated Ed25519 key if you do not already have one - ssh-keygen -t ed25519 -C john@auto1 - accepting the default location and your passphrase policy (Chapter 20, Section 20.2.1, covers the choice in detail). Install the resulting public key in ~john/.ssh/authorized_keys on auto2, using whatever access you already have to that host - your management SSH, a console session, or ssh-copy-id. Then verify the host's identity, which is the half people skip. On auto2, in the root shell (sudo -i from john's account there; leave it with exit when done), read the fingerprint of the host key the server will present:

# ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub
256 SHA256:QzNbXrcX3f0F0OemOiQlYfYSJyGuRkJTElM/oDy8vbc root@trixie (ED25519)

Take that fingerprint - or the full public key line from the same file - back to the control node through the same authenticated channel, and write it into john's known_hosts there: one line consisting of the address, the key type, and the key, for example printf '%s %s\n' 192.168.227.20 'ssh-ed25519 AAAA…' > ~/.ssh/known_hosts, followed by chmod 600 ~/.ssh/known_hosts. This is the same trust decision Chapter 20 makes at first interactive connection - there, you compare the fingerprint the client shows against one read on the server's own console; here, you make the same comparison once and record the result, because automation cannot stop to ask. What you must not do is trust a key just because the host offered it: ssh-keyscan collects keys, it does not authenticate them, and any host on the network can answer with any key it likes.

Verify the recorded trust from the control node:

$ ssh-keygen -F 192.168.227.20 -l
# Host 192.168.227.20 found: line 1 
192.168.227.20 ED25519 SHA256:QzNbXrcX3f0F0OemOiQlYfYSJyGuRkJTElM/oDy8vbc root@trixie

The fingerprint matches the one read on auto2. Now the login itself - the command id; hostname runs both queries on the remote side and exits:

$ ssh john@192.168.227.20 'id; hostname'
uid=1001(john) gid=1001(john) groups=1001(john)
auto2

The output is auto2 speaking: john's account there answers over the isolated network with key authentication, and the session ends by itself because a command was supplied. For an interactive session, plain ssh john@192.168.227.20 opens a shell there; exit it with exit or Ctrl+D.

Now describe the fleet. The project lives in ~/debian-handbook/automation/ansible, laid out as follows - the Ansible-specific tree under the workspace, with every later command in this section run from that directory:

ansible/
  ansible.cfg              project configuration
  inventory/hosts.ini      the fleet
  group_vars/all.yml       shared variables
  group_vars/vault.yml     vault-protected variables (Section 27.3.4)
  site.yml                 the playbook
  roles/web_baseline/      the applied role
    tasks/main.yml         what to do, in order
    handlers/main.yml      what to do when notified
    templates/index.html.j2  the rendered page

Create the directory tree once; every file below then has somewhere to live:

$ mkdir -p ansible/{inventory,group_vars,roles/web_baseline/{tasks,handlers,templates}}

The command is silent. The inventory, inventory/hosts.ini:

[managed]
node1 ansible_host=192.168.227.20 ansible_user=john ansible_ssh_private_key_file=/home/john/.ssh/id_ed25519

The group managed contains one host named node1 - the inventory name Ansible reports in output - with its real address, the login account, and the key to use. The configuration, ansible.cfg:

[defaults]
timeout = 60
inventory = inventory/hosts.ini
roles_path = roles
host_key_checking = True
retry_files_enabled = False
vault_password_file = /home/john/.ansible/vault-pass

[privilege_escalation]
become = True
become_method = sudo
become_user = root

Every setting is a deliberate choice: the inventory and roles path make commands work from this directory without flags; host_key_checking = True is the default and stays - automation that silently accepts unknown host keys is automation that can be pointed at the wrong machine; retry_files_enabled = False stops Ansible from dropping a .retry file into the directory after every failed run (Section 27.3.5 shows why failed reruns should be explicit); and vault_password_file points at the passphrase file Section 27.3.4 creates, outside the project. The [privilege_escalation] block makes privilege escalation the default for every play, with the play itself restating it - explicit in both places, so a reader of either file knows root is involved.

See the inventory through Ansible's eyes:

$ ansible-inventory --graph
@all:
  |--@ungrouped:
  |--@managed:
  |  |--node1

The single host sits in the managed group. Prove the whole chain - control node, key, inventory, and the remote Python that modules will execute through:

$ ansible managed -m ansible.builtin.ping
node1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3.13"
    },
    "changed": false,
    "ping": "pong"
}

The warning Ansible printed on standard error is worth one reading and then one silence: the remote Python interpreter (/usr/bin/python3.13) was discovered, so a future Python upgrade on the managed host could change which interpreter modules run under. A production inventory pins it, with node1 ... ansible_python_interpreter=/usr/bin/python3.13 in inventory/hosts.ini. The remaining Ansible output in this chapter omits that repeated warning; nothing else is altered.

27.3.2. Playbooks, Privilege Escalation, and Package Management

A playbook states what should be true on named groups of hosts; the modules turn that into commands, and Ansible records whether anything actually had to change. The playbook, site.yml:

---
- name: Apply the web baseline
  hosts: managed
  become: true
  vars_files:
    - group_vars/vault.yml
  roles:
    - web_baseline

One play: it targets the managed group, escalates to root (become: true, matching ansible.cfg), loads the vault-protected variables (Section 27.3.4), and applies the web_baseline role. The role's tasks, roles/web_baseline/tasks/main.yml:

---
- name: Validate the requested web package
  ansible.builtin.assert:
    that:
      - web_package in ['nginx', 'nginx-light']
    fail_msg: "unsupported web_package: {{ web_package }}"
  become: false

- name: Install the web package
  ansible.builtin.apt:
    name: "{{ web_package }}"
    state: present
    update_cache: true

- name: Install the site template
  ansible.builtin.template:
    src: index.html.j2
    dest: /var/www/html/index.html
    owner: root
    group: root
    mode: "0644"
  notify: Restart nginx

- name: Install the enrollment token
  ansible.builtin.copy:
    content: "{{ vault_enrollment_token }}\n"
    dest: /etc/automation-token
    owner: root
    group: root
    mode: "0600"

- name: Enable and start the web service
  ansible.builtin.service:
    name: "{{ web_service }}"
    state: started
    enabled: true

Each task is a module call with a name. become deserves one paragraph of its own, because it is where Ansible meets the security model of Chapter 5: every task marked by the play's become: true runs as root on the managed host, via sudo over the same SSH session. The remote john therefore needs sudo rights there - on the practice guests john's policy allows passwordless sudo, and with a password-asking policy you run playbooks with --ask-become-pass (or store an appropriate sudo rule per Chapter 5, Section 5.4). The assert task carries become: false deliberately: validating a variable needs no privileges, and a playbook that escalates only where required is a playbook whose audit trail says something.

The apt task shows the package-management side: state: present is idempotent - install if missing, do nothing otherwise - and update_cache: true refreshes the index the way Chapter 6 does before an upgrade. The service task states started and enabled, which maps to the systemctl verbs of Chapter 8: running now, and running after every boot.

The command surface you will actually use:

ansible-playbook option Description
--syntax-check Parse the playbook and exit; run nothing anywhere.
--check Dry run: report what would change, change nothing.
--diff Show file-level diffs of planned changes; meaningful with --check.
--limit PATTERN Restrict the run to hosts matching PATTERN.
--list-hosts Show which hosts a run would target; combined with --limit.
-e VAR=VALUE Set a variable for this run; highest precedence.
--ask-become-pass Prompt for the sudo password on managed hosts.

Check the playbook parses, then check what it would do - both against the real host, neither changing it:

$ ansible-playbook --syntax-check site.yml

playbook: site.yml
$ ansible-playbook --check --diff site.yml

PLAY [Apply the web baseline] **************************************************

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

TASK [web_baseline : Validate the requested web package] ***********************
ok: [node1] => {
    "changed": false,
    "msg": "All assertions passed"
}

TASK [web_baseline : Install the web package] **********************************
The following NEW packages will be installed:
  nginx-light
0 upgraded, 1 newly installed, 0 to remove and 81 not upgraded.
changed: [node1]

TASK [web_baseline : Install the site template] ********************************
--- before
+++ after: /home/john/.ansible/tmp/ansible-local-6015583qwp1ky/tmpzegyghm8/index.html.j2
@@ -0,0 +1,11 @@
+<!doctype html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <title>Automation baseline</title>
+  </head>
+  <body>
+    <h1>Automation baseline</h1>
+    <p>Managed host: node1</p>
+  </body>
+</html>

changed: [node1]

TASK [web_baseline : Install the enrollment token] *****************************
--- before
+++ after: /etc/automation-token
@@ -0,0 +1 @@
+example-enrollment-token-not-a-real-secret

changed: [node1]

TASK [web_baseline : Enable and start the web service] *************************
ok: [node1]

RUNNING HANDLER [web_baseline : Restart nginx] *********************************
changed: [node1]

PLAY RECAP *********************************************************************
node1                      : ok=7    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Read the run like an administrator: the assert passed with no change; the apt task in check mode printed the installation plan (NEW packages will be installed) without installing; the template diff shows the whole page as new (nothing exists at the destination yet), with the after name being Ansible's own temporary render on the control node; the token appears as a one-line file; and the service task reports ok - in check mode it only inspects, while the handler queued by the template still runs to report what a real run would restart. The recap's changed=4 is the answer to "what would this do?".

Apply it for real:

$ ansible-playbook --diff site.yml
...
TASK [web_baseline : Install the web package] **********************************
The following NEW packages will be installed:
  nginx-light
0 upgraded, 1 newly installed, 0 to remove and 81 not upgraded.
changed: [node1]
...
RUNNING HANDLER [web_baseline : Restart nginx] *********************************
changed: [node1]

PLAY RECAP *********************************************************************
node1                      : ok=7    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Selected output - the omitted sections repeat the check-mode task results exactly; this time the package actually installed, the files exist on auto2, and the handler actually restarted nginx. The service task reported ok here too: installing nginx-light on Debian starts and enables the service, so by the time the task ran, its desired state was already in place. That difference is precisely what the next check-mode run reports - nothing left to do:

$ ansible-playbook --check --diff site.yml
...
PLAY RECAP *********************************************************************
node1                      : ok=6    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Selected output - every task above the recap reported ok. The changed=0 is the idempotence proof from Section 27.1.3, now at fleet scale: the playbook states a baseline, the host conforms to it, and repeating the statement changes nothing. Confirm the delivered state from the control node - this is the reader-facing check, an HTTP request to the managed host made with curl, from the package of the same name (sudo apt install curl on auto1 if your system does not already carry it):

$ curl -fsS http://192.168.227.20/
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Automation baseline</title>
  </head>
  <body>
    <h1>Automation baseline</h1>
    <p>Managed host: node1</p>
  </body>
</html>

The template rendered on auto2 with the values from the control node (Section 27.3.3 shows where they came from).

27.3.3. Templates, Variables, Roles, and Handlers

Three constructs do most of Ansible's real work, and the role just applied uses all of them. The template, roles/web_baseline/templates/index.html.j2, is the page fetched above:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>{{ site_title }}</title>
  </head>
  <body>
    <h1>{{ site_title }}</h1>
    <p>Managed host: {{ inventory_hostname }}</p>
  </body>
</html>

Jinja2 placeholders fill from variables; the template task ships it to the destination with the stated owner, group, and mode. The variables live in group_vars/all.yml, applied to every host in the inventory:

web_package: nginx-light
web_service: nginx
site_title: Automation baseline

Precedence is what keeps variables predictable: values set with -e on the command line beat everything (Section 27.3.5 abuses that deliberately); then play-level vars and vars_files; then group_vars; then host-level inventory variables. The role refers to {{ web_package }} and {{ web_service }} without caring where they were set - that separation is the point of roles.

A role is a directory with a convention: tasks/main.yml is the ordered work, handlers/main.yml the reactions, templates/ the Jinja2 sources, files/ for verbatim copies, defaults/ for overridable defaults, and vars/ for role-internal values. Nothing needs to be registered or imported - the play that lists web_baseline under roles: gets all of it. The handler the tasks kept notifying is the third construct:

---
- name: Restart nginx
  ansible.builtin.service:
    name: "{{ web_service }}"
    state: restarted

notify: Restart nginx on the template task queues the handler; the handler runs once, at the end of the play, and only if some task reported a change. That is the correct economics: change the page thirty times in a run and nginx restarts once; change nothing and it never restarts. Handlers are how a playbook stays safe to run repeatedly - each application restarts services iff the configuration they would read actually changed.

Ad-hoc commands round out the toolkit for questions too small for a playbook:

$ ansible managed -m ansible.builtin.command -a 'stat -c %a:%U:%G /etc/automation-token'
node1 | CHANGED | rc=0 >>
600:root:root

-m selects the module and -a its argument string. The CHANGED label needs one honest caveat: command runs a shell command and reports changed because it cannot know whether the command changed anything - read-only inspection included. Use it for quick queries like this one, but state your intent with the purpose-built modules (file, stat, copy) in real playbooks, because those modules know idempotence and support check mode, which command does not.

27.3.4. Vault-Protected Data and Credential Boundaries

The playbook ships a token to every managed host, and that token started life as a line in the project:

vault_enrollment_token: example-enrollment-token-not-a-real-secret

Committed as plaintext, that file would put the credential into every copy of the repository, every backup, and every diff. ansible-vault encrypts such files symmetrically, in place. The passphrase comes from the file ansible.cfg names, which lives outside the project so it is never committed: create it with `printf '%s\n' 'your-vault-passphrase'

~/.ansible/vault-pass && chmod 600 ~/.ansible/vault-pass, choosing a real passphrase - the one used here is a practice value, and itschmod 600` is the credential's whole access policy.

ansible-vault subcommand Description
create FILE Create a new encrypted file; prompts for the passphrase.
edit FILE Decrypt to a temp file, open the editor, re-encrypt.
view FILE Print the decrypted contents without changing the file.
encrypt FILE Encrypt an existing plaintext file in place.
rekey FILE Change the passphrase.

Encrypt the file:

$ ansible-vault encrypt group_vars/vault.yml

With this ansible-core version the command is silent on success - the change is observable in the file itself:

$ head -1 group_vars/vault.yml
$ANSIBLE_VAULT;1.1;AES256

That header line is the vault format marker; the rest is the encrypted payload. Decrypting is a deliberate act:

$ ansible-vault view group_vars/vault.yml
vault_enrollment_token: example-enrollment-token-not-a-real-secret

The passphrase file supplied the key, and the plaintext appeared once, on a terminal, on request. Prove the repository carries no plaintext copy:

$ grep -R -l 'example-enrollment-token' .

The search exits 1 having printed nothing - no file under the project contains the token in readable form, because grep cannot read the vault payload. The managed host received the token during the playbook run of Section 27.3.2; check both its existence and its protection, which was the point of the mode: "0600" in the copy task:

$ ansible managed -m ansible.builtin.command -a 'cat /etc/automation-token'
node1 | CHANGED | rc=0 >>
example-enrollment-token-not-a-real-secret

The boundary deserves a precise statement, because it is easy to over-credit vault. On the control side, vault protects data at rest: the repository, its copies, and its history hold only ciphertext. It does not protect data in use - anything the playbook can render, an operator with the passphrase can read. On the managed side, nothing is encrypted at all: the token lands as a plaintext file whose safety is its 0600 root:root mode, exactly the file-level protections of Chapter 26. A fleet design therefore draws the line at delivery: short-lived or per-host credentials, delivered by a mechanism that does not persist them in a repository, beat one shared secret in a shared vault. The provisioning half of this chapter follows the same rule - Section 27.5.6 delivers preseed files that contain no long-lived secret at all, and the enrollment token that does exist is delivered by configuration management after the host exists, never baked into its image.

27.3.5. Check Mode, Limited Rollouts, and Failure Recovery

Every run so far targeted one host. Real fleets are larger, and the first discipline is to know exactly which hosts a command will touch before it touches them:

$ ansible-playbook --list-hosts site.yml --limit node1

playbook: site.yml

  play #1 (managed): Apply the web baseline TAGS: []
    pattern: ['managed']
    hosts (1):
      node1

--limit intersects the play's host pattern with the named subset. A limit that matches nothing is an error, not an empty success:

$ ansible-playbook --list-hosts site.yml --limit node9
[WARNING]: Could not match supplied host pattern, ignoring: node9
[ERROR]: Specified inventory, host pattern and/or --limit leaves us with no hosts to target.

The run exits 1 - better a loud nothing than a silent nothing. The rolling-update form of this discipline is serial: N on a play (documented Ansible behavior, not exercised with the single managed host here): the play runs in batches of N hosts, so a broken change fails on the first batch instead of the whole fleet. Check mode, --limit, and serial compose: check the whole fleet, apply to a limit of one, then widen.

Now break a run on purpose, using the highest-precedence variable from Section 27.3.3:

$ ansible-playbook -e web_package=not-a-real-package site.yml

PLAY [Apply the web baseline] **************************************************

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

TASK [web_baseline : Validate the requested web package] ***********************
[ERROR]: Task failed: Action failed: unsupported web_package: not-a-real-package
Origin: /home/john/debian-handbook/automation/ansible/roles/web_baseline/tasks/main.yml:2:3

1 ---
2 - name: Validate the requested web package
    ^ column 3

fatal: [node1]: FAILED! => {
    "assertion": "web_package in ['nginx', 'nginx-light']",
    "changed": false,
    "evaluated_to": false,
    "msg": "unsupported web_package: not-a-real-package"
}

PLAY RECAP *********************************************************************
node1                      : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

Everything about this failure is the design working. The assert was the first task with become: false, so nothing privileged had happened when it fired. The error names the value and the source file with a line and column - an operator's map straight to the problem. The assertion, the value it evaluated to, and the human-readable message are all in the result, and the recap counts failed=1 with changed=0: the host is exactly as it was. Recovery is the same discipline as Section 27.1.3 - remove the fault, run again:

$ ansible-playbook site.yml
...
PLAY RECAP *********************************************************************
node1                      : ok=6    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Selected output - the six tasks above the recap report ok with no changes: the failed assert left no half-done work behind. Two notes complete the recovery story. Because retry_files_enabled is False in ansible.cfg, the failed run left no .retry file to stale-replay later - reruns are always explicit commands. And check mode has one blind spot worth knowing: command and shell tasks are skipped in check mode (they cannot know their own effect), so a playbook that leans on them shows less than it will do - another reason to prefer purpose-built modules.