Skip to content

Configuration Management: Ansible Playbooks & Roles, Chef, Puppet, Salt ​

"Ansible automates the management of remote systems and controls their desired state." — Ansible Community Documentation, Getting started with Ansible (docs.ansible.com)

Summary: Configuration management (CM) describes how a long-lived host should look (packages, users, files, services, the app release it runs) and makes it look that way, again and again, without breaking what is already right. Ansible does it by pushing small modules over SSH from a control node, with no agent on the host; Chef, Puppet and Salt do it with an agent that pulls desired state from a server. Every outage this chapter prevents comes from one of four mistakes: a task that is not idempotent, a variable that came from the wrong place, a secret in plain text, or a change rolled out to every host at once. Focus: Where CM sits next to provisioning (Terraform), image baking (Packer, Dockerfiles) and GitOps, and the immutable-infrastructure argument; Ansible's architecture (agentless, SSH and WinRM, control node and managed nodes, static and dynamic inventory with inventory plugins, groups, group_vars and host_vars, ansible.cfg); playbooks (plays, tasks, modules, FQCN and collections, become, handlers and notify, when, loop, register, facts and gather_facts, the 22 levels of variable precedence, Jinja2 templates and filters, template vs lineinfile/blockinfile, tags, check and diff mode, --limit, serial and rolling updates, strategies, block/rescue/always, failed_when/changed_when, the idempotence contract, command vs shell and creates); roles (layout, defaults vs vars, meta dependencies, argument specs, ansible-galaxy, community.general); Ansible Vault (files, encrypt_string, vault IDs, CI) and SOPS or lookup plugins as alternatives; testing (--syntax-check, ansible-lint, Molecule, assert); Ansible in CI with OIDC-issued SSH certificates; AWX, Ansible Automation Platform and execution environments; Chef, Puppet and Salt; and two worked roles: a Go binary as a socket-activated systemd service, and a Laravel app behind PHP-FPM and Nginx with queue workers. Learning goal: Read any playbook or role and predict, per host, which tasks will report ok, changed, skipped or failed and which handlers will run; write idempotent roles for the Go service and the Laravel app that pass a second run with changed=0; know which of the 22 precedence levels a variable comes from; keep secrets out of Git and logs; roll a change through a fleet one batch at a time; and decide, for a given system, whether CM, an image, Terraform or GitOps should own each layer.

This chapter belongs to the Delivery & Infrastructure group. It owns host configuration: what is installed and running on a machine that already exists. The neighbours: creating the machines, networks and DNS in the first place is Infrastructure as Code; the pipeline that runs the playbook is CI/CD Pipelines; the pull-based reconciler for Kubernetes is GitOps; baking an image instead of configuring a host is Images & Dockerfiles; ConfigMaps, Secrets and the External Secrets Operator, which replace most of this chapter inside a cluster, are Kubernetes Config, Secrets & Storage. The Linux pieces a role manages (systemd units, users, permissions, packages) are explained in Linux for Developers, and the shell that command and shell tasks run in is Shell Scripting & Text Processing. Nginx and PHP-FPM configuration in depth is Web Servers & Reverse Proxies; SSH bastions and jump hosts are VPNs & Tunnels. Playbooks live in Git like everything else: Git & Version Control.

Everything here was checked against the saved vendor documentation on 2026-11-29 (docs.ansible.com, the ansible-lint and Molecule docs, docs.chef.io, help.puppet.com, docs.saltproject.io, developer.hashicorp.com, freedesktop.org systemd manuals, nginx.org, php.net, supervisord.org, deployer.org, laravel.com/docs/13.x). The lab ran for real: every playbook in this chapter was executed against four local host aliases with ansible_connection=local on ansible-core 2.15.13 (the last line that runs on this machine's Python 3.9; it is end of life, see the version note), twice where idempotence is the claim, and the transcripts are saved. Tasks that need root, systemd, apt or real hosts are written for Ubuntu 24.04 and marked expected, not run.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why CM exists; mutable vs immutable; the trade-offsWhy it exists
CFEngine 1993, Puppet, Chef 2009, Salt 2011, Ansible 2012, ansible-coreWhere it comes from
Provisioning vs configuration, image baking, Packer, immutable infrastructure, driftCM vs provisioning vs images vs GitOps
Agentless, SSH, WinRM, control node, managed node, modulesAnsible architecture
Static inventory, dynamic inventory, inventory plugins, groups, group_vars, host_varsInventory
ansible.cfg, forks, pipelining, fact cachingansible.cfg
Playbook, play, task, module, FQCN, ansible.builtin, collectionsPlaybooks
become, sudo, become_userPrivilege escalation
Facts, gather_facts, setup module, register, when, loopFacts, conditions, loops
Variable precedence (22 levels), defaults vs vars, group merge orderVariables and precedence
Jinja2, templates, filters, template vs lineinfile vs blockinfileTemplates
Idempotence, ok/changed/failed, command vs shell, creates, changed_whenIdempotence
Handlers, notify, listen, flush_handlersHandlers
Check mode (--check), diff mode (--diff)Check and diff
Tags, --tags, --limitTags and limits
serial, rolling update, max_fail_percentage, strategy, free strategyRolling updates
block/rescue/always, failed_when, ignore_errorsError handling
Roles, role layout, meta dependencies, argument specs, ansible-galaxyRoles
Ansible Vault, ansible-vault encrypt, vault ID, encrypt_string, SOPS, lookup pluginsSecrets
--syntax-check, ansible-lint, Molecule, assert moduleTesting
Running playbooks from GitHub Actions with OIDC-issued SSH certificatesAnsible in CI
AWX, Ansible Automation Platform, execution environmentsAWX and AAP
Chef (cookbooks, recipes), Puppet (manifests, agent, Bolt), Salt (minions, states, pillar, grains, reactor)Chef, Puppet, Salt
When not to use CMWhen not to
Push vs pull, agent vs agentless, side by sideCompared
What happens when a task runs; knobs; error messagesMechanics
CodeGo, Laravel
Classic problems and fixesSolving the classic problems
Which tool, which secret store, which deploy toolChoosing
From one VM to a fleetIn architecture
Commands with real outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary in four products.

ConceptAnsiblePuppetChef InfraSalt
ModelPush from a control node (ansible-pull exists, rare)Pull: agent asks the primary server for a catalogPull: Chef Infra Client fetches cookbooks from Chef Infra ServerPush and pull: master publishes to minions over an event bus; salt-ssh is agentless
Agent on the hostNone; needs SSH (or WinRM) and Pythonpuppet agentchef-clientsalt-minion
LanguageYAML + Jinja2Puppet DSL (declarative)Ruby DSLYAML + Jinja (SLS files)
Unit of desired stateTask calling a moduleResource in a manifestResource in a recipeState in an SLS file
Reusable packageRole, collection (Galaxy)Module (Forge)Cookbook (Supermarket)Formula
Host factsFacts (setup module)Facts (Facter)Ohai attributesGrains
Per-host data and secretsInventory vars, Ansible VaultHieraData bags, attributesPillar
"Restart if changed"Handler + notify~> / notify refreshnotifies :restartwatch / onchanges
OrderTop to bottomDependency graph (->, require)Top to bottomRequisites, then file order
Ad hoc executionansible all -m ...Puppet Boltknife sshsalt '*' cmd.run
GUI / API / RBACAWX, Ansible Automation PlatformPuppet EnterpriseChef AutomateSalt master API, SaltStack Config

What runs where in this chapter's two roles.

StepGo service (go_service role, orders-api)Laravel app (laravel_app role, shop)Lab status
1 Basecommon role (meta dependency): layout, packages, timezoneSameLayout ran; packages expected, not run
2 AccountSystem user orders-api, no shellSystem user shop; php8.4-fpm, nginx, supervisor packagesExpected, not run
3 ReleaseChecksummed binary into releases/1.4.2/, keep 3 releasesGit checkout + Composer into releases/<id>/, shared storage and .envRan (binary copied from the controller; code copied from the snippet tree)
4 ConfigEnv file from Vault (0640, no diff), socket + service units.env from Vault, PHP-FPM pool, Nginx site, queue worker unit or Supervisor programRan (files rendered under the lab root)
5 Build stepsNone (static binary)php artisan optimize once per release (creates), php artisan migrate --force on one host (changed_when)Ran against an artisan stand-in
6 Switchcurrent symlink, handler restarts the servicecurrent symlink, handlers reload PHP-FPM, Nginx and restart queue workersRan; service handlers are stand-ins
7 Verifyuri on /healthz + assert on the versionuri on /up through NginxExpected, not run; file-level asserts ran

The rules in one table.

RuleWhyWhere
A second run must report changed=0Anything else is drift you are causing yourself, and it fires handlers (restarts) for nothingIdempotence
Prefer a real module to command/shell; if you must, add creates or changed_whenA command always reports changed and cannot be checked in --checkIdempotence
Restart in handlers, never in tasksA handler runs once, only if something changedHandlers
Knobs in defaults/, constants in vars/Role vars beat inventory; callers cannot override themPrecedence
Secrets in Vault (or SOPS / a lookup), referenced through vault_ variables; diff: false / no_log on tasks that render themVault protects data at rest only; --diff and -v print valuesSecrets
Use FQCNs (ansible.builtin.copy)No ambiguity between collections; ansible-lint enforces itPlaybooks
serial + max_fail_percentage for anything that restartsA bad change stops at the first batch, not at the whole fleetRolling updates
--check --diff before every apply, in CIYou read the change before it happens; drift shows up as a diffCheck and diff
Do not configure containers with CMImages and Kubernetes manifests already describe that stateWhen not to
Four tools, four jobs: who owns which layerProvisioningTerraform, Pulumi,CloudFormationVPC, VMs, LB, DNS,IAM, managed DBs"what exists"Image bakingPacker (AMI, qcow2),Dockerfile, BuildKitOS + runtime + app,built once, versioned"what boots"Config managementAnsible, Chef,Puppet, Saltpackages, users, files,services, app deploys"how a host is set up"GitOpsArgo CD, FluxKubernetes manifests,Helm, Kustomize,reconciled from Git"what runs in k8s"Packer can run Ansible inside the buildMutable serverchanged in place for years; drifts (hand edits,partial runs); fixed by re-running the CM toolImmutable servernever modified after boot; a change = a new imageand a replacement; CM only at bake time

Why it exists ​

A server that someone set up by hand works until it has to be rebuilt, copied or audited. Then nobody remembers which packages were installed, which line was changed in php.ini, or why. Fowler named the result: "The result is a unique snowflake - good for a ski resort, bad for a data center." Configuration management replaces the memory with a description in Git and a program that makes every host match it, so building the tenth server is the same as building the first and a hand edit is undone at the next run.

The price is a second system to run and a contract to keep: every task must be safe to repeat. A playbook that restarts PHP-FPM on every run, or a recipe that appends the same line twice, is worse than no automation because it fails quietly and at scale.

Simpler choiceRicher choiceWhat you buyWhat you pay
SSH in and type commandsA playbook in GitRepeatable, reviewable, auditable changesLearning the tool; keeping tasks idempotent
Shell script run over SSHModules with declared stateSafe reruns, --check, --diff, per-task statusLess freedom than a script
One big playbookRoles with defaults, handlers, testsReuse across services and teamsA layout and precedence rules to learn
All hosts at onceserial batches with a failure thresholdA bad change hits one host, not allLonger deploys
Push on demand (Ansible)Agent pulling every 30 minutes (Puppet, Chef, Salt)Drift is corrected without anyone actingAn agent per host and a server to operate
Mutable hosts, configured in placeImmutable images, replaced on changeNo drift, fast rollback by imageAn image pipeline; state must live elsewhere
Plain-text varsAnsible Vault, SOPS or an external secret storeSecrets safe in GitPassword and key distribution
Hand-run from a laptopRun from CI or AWX with short-lived credentialsAudit log, no personal keys on serversPipeline and identity setup

The analogy used through this page: a building's maintenance checklist. The checklist (the playbook) does not say "paint the wall"; it says "the wall is white". A caretaker (Ansible) walks through the building (the inventory), floor by floor (the batches), and for each line checks first, acts only if needed, and ticks "ok" or "changed". Some lines say "if you changed the boiler settings, restart the boiler at the end of the round" (a handler): the boiler is restarted once, however many settings changed. The building manager's notes per floor (group_vars) and per room (host_vars) say what "white" means here. The keys to the plant room are in a sealed envelope (the vault) that only the caretaker opens. Puppet's model is a caretaker living on every floor who rereads the checklist every half hour. The immutable alternative is to stop maintaining floors and swap in a new prefabricated one (an image).

Three common misunderstandings, up front ​

  1. "Ansible is idempotent." Modules can be; your playbook is idempotent only if every task is. command, shell and a copy of a generated timestamp report changed every time. The lab proves it the hard way: the second run of the first Laravel role draft reported changed=2 on both hosts (a creates path that never matched, and a migration command whose result could not be trusted) until both were fixed. See Idempotence and Lab.
  2. "Vault keeps my secrets secret." The docs: "Encryption with Ansible Vault ONLY protects 'data at rest'." Once decrypted for a run, a secret prints in --diff, in -v output and in ansible-inventory --list (shown in the lab). See Secrets.
  3. "Variables in a role are the role's defaults." Only defaults/main.yml is low-precedence. vars/main.yml sits at level 15 of 22 and beats every inventory variable; a caller who sets the same name in group_vars is silently ignored. See Variables and precedence.

Where it comes from ​

WhenWhat happenedSource
1993CFEngine: "The CFEngine project began in 1993" (Mark Burgess, Oslo University), the first widely used convergent CM toolWikipedia, CFEngine (secondary)
2005Puppet (Luke Kanies): a declarative language compiled into catalogs that agents applyWikipedia, Puppet (software) (secondary); help.puppet.com
January 2009Chef (Opscode), Ruby DSL, Chef server and clientWikipedia, Progress Chef (secondary)
19 March 2011Salt (Thomas S. Hatch): remote execution over a message bus, then statesWikipedia, Salt (software) (secondary)
2012Ansible, "Originally written by Michael DeHaan in 2012", agentless over SSHWikipedia, Ansible (software) (secondary)
16 October 2015"Red Hat to Acquire IT Automation and DevOps Leader Ansible"Red Hat press release
After 2.9The engine and the content split: ansible-core (2.11, 2.12, ...) versus the community ansible package (2.10, then 3.0.0 ...) that bundles "more than 85 Collections"; modules get FQCNs (ansible.builtin.copy)Ansible Releases and maintenance; Using Ansible collections
September 2020"VMware acquired SaltStack" (VMware later became part of Broadcom)Wikipedia, Salt (software) (secondary)
22 May 2023ansible-core 2.15 GA; 2.15.13 (4 Nov 2024) is the last 2.15 release, end of life Nov 2024Ansible Releases and maintenance; 2.15 changelog
May 2026ansible-core 2.21 GA (control node Python 3.12-3.14); 2.22 GA Nov 2026 (Python 3.13-3.15)Ansible Releases and maintenance
2026Chef Infra Client 19 docs, Puppet Core 9.1.4 ("Last published: November 19, 2026"), Molecule's "ansible-native" configuration alongside the older driver modeldocs.chef.io, help.puppet.com, Molecule docs

Two schools meet in today's tools. The convergent agent school (CFEngine, Puppet, Chef) puts a daemon on every host that periodically compares the host to a model and repairs differences; it is excellent at stopping drift and needs a server, certificates and an agent lifecycle. The orchestration school (Ansible, Salt's remote execution, Puppet Bolt) runs an ordered list of steps from one place when a human or a pipeline asks; it is excellent for deploys and rolling changes and only corrects drift when it runs. Containers moved most application configuration into images and Kubernetes manifests, which shrank CM's job to the hosts underneath and to the VMs that still run applications directly.

Version note: which ansible-core this page ran ​

LineGAEnd of lifeControl node PythonTarget PythonUsed here
2.1522 May 2023Nov 20243.9-3.112.7, 3.5-3.11The lab (2.15.13), because the build machine has CPython 3.9.6 only
2.2003 Nov 2025May 20273.12-3.143.9-3.14
2.21May 2026Nov 20273.12-3.143.9-3.14Recommended pin in the CI workflow
2.22Nov 2026May 20283.13-3.153.9-3.15Current at the time of writing

The modules and keywords the lab uses are documented on the current (latest) docs pages saved for this chapter, so the roles carry over; the 2.15 transcripts are still 2.15 output, and newer lines print some messages differently. Run production on a maintained line, and read the porting guides when you move up: "X.Y.0 releases do not carry any guarantee of 100% backwards compatibility with the version before it."

The concept catalogue ​

Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix. Code blocks marked "ran" come from the lab transcripts; everything else is labelled.

Configuration management vs provisioning vs image baking vs GitOps; immutable infrastructure and drift Must-know ​

In plain words: Provisioning creates machines and networks. Configuration management sets up what is inside a machine that already exists. Image baking does that setup once, at build time, and boots copies of the result. GitOps keeps a Kubernetes cluster equal to what is in Git. Drift is the gap between what the description says and what the host really has.

Common misunderstanding: "Terraform and Ansible do the same thing, pick one." The provisioning vs configuration split is about the API each one talks to. Terraform talks to cloud APIs and keeps a state file of resources it created; Ansible talks to an operating system over SSH and keeps no state at all, it re-checks the host on every run. Terraform can run a script at boot (user_data, cloud-init) and Ansible can call cloud APIs (amazon.aws.ec2_instance), but each is weak at the other's job.

Definition:

  • Provisioning: creating infrastructure resources (VPC, VM, load balancer, DNS record, IAM role, managed database) through a provider API. Owner: Infrastructure as Code.
  • Configuration management: converging the inside of a host (packages, users, files, services, kernel parameters, the application release) to a declared state, repeatedly.
  • Image baking: producing a machine or container image with that state already applied. HashiCorp: "Packer is a community tool for creating identical machine images for multiple platforms from a single source configuration", and "when building images, Packer is able to use tools like Chef or Puppet to install software onto the image" (Ansible too, through its provisioner). For containers the image is a Dockerfile build: Images & Dockerfiles.
  • Immutable infrastructure: Fowler: "An Immutable Server is the logical conclusion of this approach, a server that once deployed, is never modified, merely replaced with a new updated instance."
  • Drift: any difference between declared and actual state: a hand edit, a failed half-run, a package upgraded by unattended-upgrades, a file a developer "just fixed". Fowler on long-lived servers: "In practice, however, it isn't feasible to keep servers completely consistent using current automated configuration management tools, so over time configuration synchronization leads to inconsistency."
text
1  terraform apply          -> VPC, 3 VMs (orders-1..3), LB, DNS          (provisioning)
2  packer build             -> image orders-base-2026-11 (Ubuntu + agent)  (image baking, optional)
3  ansible-playbook site.yml -> users, units, env file, binary 1.4.2       (configuration)
4  ... weeks pass: someone edits /etc/systemd/system/orders-api.service by hand ...
5  ansible-playbook site.yml --check --diff -> "-# drift"                  (drift detected)
6  ansible-playbook site.yml                -> changed=1, handler restarts (drift corrected)
   immutable alternative to 3-6: bake 1.4.2 into the image, replace the VMs, never edit them

Real scenarios:

  • A team runs Ansible against 40 Ubuntu VMs every night in --check --diff mode and pages nobody; the report shows that 3 hosts have a hand-edited sshd_config. That is drift detection without auto-repair.
  • A fleet of autoscaled VMs boots from a Packer image that already contains the Go binary; Ansible runs only inside the Packer build. No host is ever configured after boot (immutable).
  • A Laravel app moves to Kubernetes: the PHP-FPM, Nginx and queue-worker configuration moves into the image and the Deployment; Ansible keeps managing only the database VMs and the bastion.
LayerTool familyTalks toKeeps state?Typical products
Cloud resourcesProvisioningCloud/provider APIsYes (state file)Terraform, OpenTofu, Pulumi, CloudFormation, CDK
Machine imageImage bakingHypervisor / cloud image API, then the OS during buildImage versionsPacker, EC2 Image Builder
Container imageImage bakingBuildKitRegistry digestsDocker, BuildKit, Buildah
Host insideConfiguration managementSSH/WinRM, or an agent on the hostNo (Ansible); last report (Puppet/Chef)Ansible, Puppet, Chef, Salt, CFEngine
Kubernetes objectsGitOpsKubernetes APIGit + clusterArgo CD, Flux, Helm, Kustomize

Fix / how to use it: give every layer one owner: Terraform creates the VMs and outputs their addresses (or tags them for a dynamic inventory); Packer or a Dockerfile bakes what never changes between deploys; Ansible owns what changes on a living host (release, config, users); Argo CD or Flux owns anything inside Kubernetes. Run --check --diff on a schedule to see drift even when you do not deploy.

Ansible architecture: agentless, control node, managed nodes, SSH and WinRM, modules Must-know ​

In plain words: You install Ansible on one machine, the control node. It reads a list of hosts, connects to each over SSH, copies a small program (a module) there, runs it, reads back a JSON answer and deletes it. Nothing stays running on the host. That is what agentless means.

Common misunderstanding: "Agentless means nothing is needed on the host." A Linux managed node needs an SSH server and a Python interpreter (the modules are Python); a Windows host needs WinRM or SSH and PowerShell. "Agentless" means no long-running Ansible daemon, no certificate enrolment and no server to keep in sync, not zero requirements. The raw module is the exception that works without Python, which is how you bootstrap one.

Definition (Ansible docs, Ansible concepts):

  • Control node: "The machine from which you run the Ansible CLI tools (ansible-playbook, ansible, ansible-vault and others)." Laptops, CI runners and AWX pods all qualify; "Multiple control nodes are possible, but Ansible itself does not coordinate across them". It can also be a container: "You can also run Ansible in containers known as Execution Environments."
  • Managed node: "Also referred to as 'hosts', these are the target devices (servers, network appliances or any computer) you aim to manage with Ansible." "Ansible is not normally installed on managed nodes, unless you are using ansible-pull, but this is rare and not the recommended setup."
  • Module: "The code or binaries that Ansible copies to and executes on each managed node (when needed) to accomplish the action defined in each Task."
  • Connection plugins: ssh (OpenSSH, the default), paramiko, winrm and psrp for Windows, local (run on the control node itself, used by this chapter's lab), docker and community.docker.docker for containers, kubernetes.core.kubectl, amazon.aws.aws_ssm for SSM Session Manager.
  • WinRM: the docs: "WinRM is a management protocol used by Windows to remotely communicate with another server"; Ansible talks to it with ansible_connection: winrm and authentication such as NTLM, Kerberos or CredSSP.
text
control node                                   managed node web1 (sshd, python3)
1  read inventory, vars, playbook
2  render task args with Jinja2 (on the controller)
3  build module payload (AnsiballZ zip)  --SSH-->  4  write to ~/.ansible/tmp/... (or pipe over stdin with pipelining)
                                                    5  python3 module: compare desired vs actual, act if needed
6  read JSON {"changed": true, ...}     <--SSH--    7  remove the temp dir
8  record ok/changed/failed, queue handlers, next host (forks in parallel), next task

Real scenarios:

  • A minimal Debian cloud image has no Python: the first task fails with a module error until a raw: apt-get install -y python3 bootstrap runs (or the image includes it).
  • A security team forbids long-running agents on PCI hosts: Ansible needs only SSH keys and a sudo rule, both of which the team already audits.
  • A Windows fleet is managed with ansible.windows.win_* modules over WinRM HTTPS with Kerberos from a Linux control node.
RequirementAnsiblePuppetChef InfraSalt
Daemon on the hostNopuppet agentchef-client (daemon or timer)salt-minion (none with salt-ssh)
TransportSSH, WinRM/PSRP, local, docker, SSMHTTPS to the primary server (8140)HTTPS to Chef Infra ServerZeroMQ to the master (4505/4506); SSH for salt-ssh
Trust bootstrapSSH key or certificate + sudo ruleAgent certificate signed by the Puppet CAClient key registered with the serverMinion key accepted on the master
Interpreter on the hostPython (or PowerShell)Bundled Ruby in the agent packageBundled Ruby in the client packageBundled Python in the minion package

Fix / how to use it: bake python3 and your SSH CA public key into the base image; give Ansible a dedicated deploy user with a narrow sudo rule; turn on SSH multiplexing and pipelining in ansible.cfg (shown below) so a task costs one round trip instead of several.

Inventory: static and dynamic, inventory plugins, groups, group_vars and host_vars Must-know ​

In plain words: The inventory is the list of hosts and the groups they belong to, plus variables per group and per host. It can be a file you write (static inventory) or something a plugin builds by asking a cloud API every run (dynamic inventory).

Common misunderstanding: "A host belongs to one group." A host belongs to as many groups as you like (web2 is in go_service and production in the lab). That is how you slice by role and by environment at once; the price is that two groups at the same depth can set the same variable, and then the alphabetically later group wins.

Definition:

  • Two groups always exist: "Even if you do not define any groups in your inventory, Ansible creates two default groups: all and ungrouped."
  • Static inventory: INI or YAML files (or a directory of them). INI supports ranges (shop-web-[1:3].prod) and [group:children].
  • Dynamic inventory: "Ansible supports two ways to connect with external inventory: Inventory plugins and inventory scripts. ... We recommend plugins over scripts for dynamic inventory." Inventory plugins such as amazon.aws.aws_ec2 and google.cloud.gcp_compute read a YAML config (the file name must match what the plugin expects, for example ending in aws_ec2.yml), call the API, and build groups from tags with keyed_groups.
  • group_vars / host_vars: directories next to the inventory (or the playbook) with one file or directory per group or host. "Ansible reads and loads files from the top directory down in alphabetically sorted order."
  • Merge order: "all group (because it is the 'parent' of all other groups) parent group child group host"; groups at the same level merge alphabetically unless ansible_group_priority says otherwise.

The lab inventory, four aliases on one machine:

yaml
# Local lab inventory: four aliases, all on this machine, each with its own
# directory tree under $LAB_ROOT/<host> (scripts/lab.sh sets it), so plays, --limit, serial and
# group_vars behave as they would on four servers.
all:
  vars:
    ansible_connection: local
    ansible_python_interpreter: "{{ ansible_playbook_python }}"
  children:
    go_service:
      hosts:
        web1:
        web2:
    laravel:
      hosts:
        app1:
        app2:
    staging:
      hosts:
        web1:
        app1:
    production:
      hosts:
        web2:
        app2:
yaml
# Applies to every host. Local lab: no root, no systemd, no packages.
cm_manage_system: false
# Absolute on purpose: ansible-playbook resolves a relative module path
# against the playbook directory, not the shell's working directory.
cm_root: "{{ lookup('ansible.builtin.env', 'LAB_ROOT') }}/{{ inventory_hostname }}"
demo_color: from group_vars/all

The production inventory, static (parsed for real with ansible-inventory --graph) and dynamic (expected, not run). The static file is called hosts, not hosts.ini, for a reason the lab found: when -i points at a directory, Ansible skips files whose extension is in INVENTORY_IGNORE_EXTS, and the 2.15 default list contains .ini and .cfg (transcript 27). With hosts.ini plus the two cloud plugin files in one directory and no cloud collections installed, ansible-inventory -i inventories/production --graph printed "No inventory was parsed, only implicit localhost is available" and an empty @all (transcript 39). The plugin files therefore live in inventories/cloud/, used only where cloud credentials exist.

ini
# Static INI inventory for the real fleet (not used by the local lab).
# No .ini extension on purpose: when -i points at a directory, files ending
# in .ini are skipped (INVENTORY_IGNORE_EXTS includes .ini and .cfg).
# Host aliases on the left; how to reach them in host variables.
[go_service]
orders-1.prod ansible_host=10.20.1.11
orders-2.prod ansible_host=10.20.1.12
orders-3.prod ansible_host=10.20.1.13

[laravel_web]
shop-web-[1:3].prod

[laravel_worker]
shop-worker-1.prod ansible_host=10.20.2.21

[laravel:children]
laravel_web
laravel_worker

[production:children]
go_service
laravel

[all:vars]
ansible_user=deploy
ansible_port=22
yaml
# Dynamic inventory: the amazon.aws.aws_ec2 inventory plugin (needs boto3 and
# AWS credentials; expected, not run here). The file name must end in
# aws_ec2.yml or aws_ec2.yaml for the plugin to accept it. Kept out of
# inventories/production so CI can parse that directory without AWS access;
# use -i inventories/cloud/prod.aws_ec2.yml where credentials exist.
plugin: amazon.aws.aws_ec2
regions:
  - eu-central-1
filters:
  instance-state-name: running
  tag:ManagedBy: ansible
# Build groups from tags: tag Role=go_service -> group go_service.
keyed_groups:
  - key: tags.Role
    separator: ""
  - key: tags.Env
    separator: ""
hostnames:
  - tag:Name
  - private-dns-name
compose:
  # Connect over the private address (through a bastion, see ssh config).
  ansible_host: private_ip_address
cache: true
cache_plugin: ansible.builtin.jsonfile
cache_connection: .ansible-inventory-cache
cache_timeout: 300
bash
# ran: the production inventory directory, as Ansible sees it (transcript 41)
$ ansible-inventory -i inventories/production --graph
@all:
  |--@ungrouped:
  |--@production:
  |  |--@go_service:
  |  |  |--orders-1.prod
  |  |  |--orders-2.prod
  |  |  |--orders-3.prod
  |  |--@laravel:
  |  |  |--@laravel_web:
  |  |  |  |--shop-web-1.prod
  |  |  |  |--shop-web-2.prod
  |  |  |  |--shop-web-3.prod
  |  |  |--@laravel_worker:
  |  |  |  |--shop-worker-1.prod

Real scenarios:

  • An autoscaling group replaces VMs daily; a static file is wrong within hours. The aws_ec2 plugin with keyed_groups on the Role tag always targets what is running.
  • A host is accidentally tagged both Env=staging and Env=production and receives production secrets. The Go inventory check catches it before the playbook runs.
  • A bastion-only network: ansible_ssh_common_args: '-o ProxyJump=bastion.example.com' in group_vars/production.yml (see VPNs & Tunnels).
Inventory sourceHow it is enabledGood forWatch out
INI fileDefault (ini plugin)Small, stable fleetsValues are strings unless declared in YAML vars files
YAML fileDefault (yaml plugin)Nested groups, typed varsIndentation; hosts: entries need a trailing colon
amazon.aws.aws_ec2Collection + boto3; file *.aws_ec2.ymlEC2 fleets, autoscalingAPI rate limits: enable cache: true
google.cloud.gcp_computeCollection + google-auth; file ending gcp_compute.yml or gcp.ymlGCE fleetsLabels vs tags naming
constructedBuilt-inGroups from existing vars (keyed_groups, groups)Runs after the sources it reads
Inventory scriptExecutable printing --list JSONLegacy CMDBsSlower; no caching or composition
A directory of the above-i inventories/productionOne environment = one directoryFiles ending in .ini, .cfg, .txt, .md... are skipped (INVENTORY_IGNORE_EXTS)

Fix / how to use it: one inventory directory per environment (inventories/production, inventories/staging) with extension-less INI files or YAML, dynamic where machines come and go, environment-wide values in group_vars/all, and a CI step that validates the merged result (ansible-inventory --list piped into a checker, shown in Go).

ansible.cfg: the knobs that matter Important ​

In plain words: ansible.cfg holds the defaults for every Ansible command run in that directory: which inventory, how many hosts at once, how to connect.

Common misunderstanding: "Ansible merges all my config files." It reads exactly one: the first of ANSIBLE_CONFIG, ./ansible.cfg, ~/.ansible.cfg, /etc/ansible/ansible.cfg. A personal ~/.ansible.cfg is silently ignored the moment the project has its own. Every setting also has an environment variable (ANSIBLE_FORKS, ANSIBLE_PIPELINING...) that overrides the file.

Definition: an INI file with sections such as [defaults], [privilege_escalation], [ssh_connection], [inventory]. Relative paths in it are resolved against the file's own directory. Ansible ignores an ansible.cfg in a world-writable current directory, for security.

ini
# ansible.cfg -- project-level configuration. Ansible reads the first of:
# ANSIBLE_CONFIG, ./ansible.cfg, ~/.ansible.cfg, /etc/ansible/ansible.cfg
# (only one file is used; settings are not merged across files).
[defaults]
# Relative paths here resolve against this file's directory.
inventory = inventories/local/hosts.yml
roles_path = roles
collections_path = collections
# 5 is the default; raise it for big fleets (one fork = one host in flight).
forks = 20
# Pick the Python on the managed node without a warning per host.
interpreter_python = auto_silent
# Never answer "yes" to an unknown SSH host key on someone's behalf.
host_key_checking = True
retry_files_enabled = False
# Show skipped hosts, and timings per task (profile_tasks lives in ansible.posix;
# requirements.yml installs it).
display_skipped_hosts = True
callbacks_enabled = ansible.posix.profile_tasks
# Facts are expensive at scale: cache them between runs.
gathering = smart
fact_caching = jsonfile
fact_caching_connection = .ansible-facts
fact_caching_timeout = 3600

[privilege_escalation]
# become is switched on per play, never globally.
become = False
become_method = sudo

[ssh_connection]
# One SSH connection per host, reused for 60 s, and modules piped over stdin
# instead of copied (pipelining needs "Defaults !requiretty" in sudoers).
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
text
which config wins (first match only)
1  ANSIBLE_CONFIG=/path/to/ansible.cfg      <- scripts/lab.sh sets this
2  ./ansible.cfg (current directory)         <- skipped if the directory is world-writable
3  ~/.ansible.cfg
4  /etc/ansible/ansible.cfg
then: ANSIBLE_<SETTING> environment variables override single settings; CLI flags override both

Real scenarios:

  • A run against 300 hosts takes 40 minutes with the default 5 forks and 6 minutes with forks = 50 and pipelining on.
  • pipelining = True breaks become on hosts whose sudoers still has requiretty (sudo refuses to run without a terminal); the fix is the sudoers default (Defaults !requiretty), not turning pipelining off.
  • host_key_checking = False copied from a blog post lets a man-in-the-middle answer for a production host; CI should ship a known_hosts (or an SSH CA line) instead.
SettingDefaultWhy change it
forks5Hosts in flight per task; raise for fleets
pipeliningFalseFewer SSH round trips; needs no requiretty
ssh_args-C -o ControlMaster=auto -o ControlPersist=60sKeep multiplexing; add ProxyJump per group instead
host_key_checkingTrueKeep it True; distribute host keys or an SSH CA
gatheringimplicitsmart + a fact cache avoids re-gathering
fact_cachingmemoryjsonfile or redis to keep facts between runs
interpreter_pythonautoauto_silent hides the discovery warning
callbacks_enablednoneansible.posix.profile_tasks for per-task timings
vault_identity_listnoneDefault vault IDs, for example prod@scripts/vault-pass.sh
retry_files_enabledFalseKeep False; use --limit @file only on purpose

Fix / how to use it: commit one ansible.cfg per repository; set the inventory, roles path and collections path relative to it; never commit host_key_checking = False.

Playbooks, plays, tasks, modules; FQCN, ansible.builtin and collections Must-know ​

In plain words: A playbook is a YAML file with one or more plays. A play says "on these hosts, as this user, run these tasks (and roles)". A task calls one module with arguments. Modules ship in collections, and you name them by their full name, for example ansible.builtin.copy.

Common misunderstanding: "A playbook is a script." It is data: "Ansible playbooks are pure machine-parseable YAML", and "Ansible allows Jinja2 loops and conditionals in templates but not in playbooks." Control flow is expressed with keywords (when, loop, block, notify), not with if statements.

Definition (Ansible concepts): plays are "The main context for Ansible execution, this playbook object maps managed nodes (hosts) to tasks"; a play "basically consists of an implicit loop over the mapped hosts and tasks". A task is "The definition of an 'action' to be applied to the managed host." Collections package modules, plugins and roles under a namespace.collection name; ansible.builtin ships inside ansible-core, everything else (community.general, ansible.posix, amazon.aws) is installed with ansible-galaxy collection install. FQCN (fully qualified collection name) is namespace.collection.module. The docs recommend it even for builtins: "we recommend you use the Fully Qualified Collection Name (FQCN) ansible.builtin.systemd_service for easy linking to the module documentation and to avoid conflicting with other collections that may have the same module name."

The chapter's one entry point, used both for the real fleet and for the lab:

yaml
# The one entry point, for the real fleet and for the local lab alike:
#   ansible-playbook -i inventories/production playbooks/site.yml   (real hosts)
#   ansible-playbook playbooks/site.yml                              (lab, ansible.cfg inventory)
- name: Go service, rolling, one host first
  hosts: go_service
  become: "{{ cm_manage_system | bool }}"
  # Canary of 1, then half of the rest at a time; stop the play if any host fails.
  serial:
    - 1
    - "50%"
  max_fail_percentage: 0
  gather_facts: true
  pre_tasks:
    - name: Take the host out of the load balancer
      ansible.builtin.debug:
        msg: "drain {{ inventory_hostname }} (in production: a delegate_to task against the LB API)"
      tags: [always]
  roles:
    - role: go_service
  post_tasks:
    - name: Put the host back
      ansible.builtin.debug:
        msg: "enable {{ inventory_hostname }}"
      tags: [always]

- name: Laravel app
  hosts: laravel
  become: "{{ cm_manage_system | bool }}"
  serial: "50%"
  gather_facts: true
  roles:
    - role: laravel_app
yaml
# ansible-galaxy collection install -r requirements.yml -p collections
# Production pins (Galaxy, 2026-11-29): community.general 14 declares
# requires_ansible >= 2.19 and ansible.posix 2.2.2 >= 2.16, so these need a
# current ansible-core. The lab on this page ran on ansible-core 2.15.13 with
# community.general 10.7.9 and ansible.posix 1.6.2 (both declare >= 2.15).
collections:
  - name: community.general
    version: ">=14.0.0,<15.0.0"
  - name: ansible.posix
    version: ">=2.2.0,<3.0.0"
  - name: amazon.aws
    version: ">=12.1.0,<13.0.0"
  - name: google.cloud
    version: ">=1.16.0,<2.0.0"
  - name: community.sops
    version: ">=2.5.0,<3.0.0"
text
ansible-playbook playbooks/site.yml
1  parse YAML, resolve roles and imports (static), FQCNs -> plugins      (--syntax-check stops here)
2  play 1 "Go service": hosts=go_service -> [web1, web2], serial [1, 50%] -> batches [web1], [web2]
3  batch 1: gather facts on web1, pre_tasks, role common (dependency), role go_service, post_tasks
4  batch 2: the same on web2
5  play 2 "Laravel app": hosts=laravel -> [app1, app2], serial 50% -> [app1], [app2]
6  PLAY RECAP: one line per host

Real scenarios:

  • Two collections ship a module called docker_container; with short names, the one found first wins. With community.docker.docker_container there is no question.
  • A role written for Ansible 2.9 uses apt: and service: short names; it still works through the ansible.builtin redirect, but ansible-lint's fqcn rule flags every line.
  • Upgrading community.general from 10.x to 14.x drops support for ansible-core 2.15 (requires_ansible), so the collection pin and the core pin must move together.
Module (FQCN)Use it forInstead of
ansible.builtin.copy (copy module)A file from the controller, or content:shell: echo ... > file
ansible.builtin.template (template module)A file rendered with Jinja2copy + lineinfile edits
ansible.builtin.file (file module)Directories, symlinks, modes, state: absentmkdir -p, ln -s, rm -rf
ansible.builtin.lineinfile / blockinfileOne line or one marked block in a file you do not ownTemplating a whole distro file
ansible.builtin.package (package module)Packages with the host's package managerapt/dnf when the role is cross-distro
ansible.builtin.aptDebian/Ubuntu packages, update_cache, cache_valid_timecommand: apt-get install
ansible.builtin.service (service module)Start, stop, reload, enable, any init systemcommand: systemctl ...
ansible.builtin.systemd_service (systemd module; systemd is an alias)systemd specifics: daemon_reload, masked units, scopecommand: systemctl daemon-reload
ansible.builtin.user / groupAccountsuseradd
ansible.builtin.gitChecking out a releasecommand: git clone
ansible.builtin.get_urlDownload with checksum:curl in shell
ansible.builtin.uriHTTP checks, API callscurl in shell
ansible.builtin.assert (assert module)Fail with a message unless conditions holdfail + when
ansible.builtin.command / shellOnly when no module exists-
community.general.supervisorctl, community.general.composer, community.general.timezoneSupervisor programs, Composer, timezonecommand:

Fix / how to use it: FQCNs everywhere, a requirements.yml with version ranges for every collection, and ansible-galaxy collection install -r requirements.yml -p collections in CI so every run uses the same plugin code.

Privilege escalation: become, sudo, become_user Important ​

In plain words: You log in as an ordinary user (deploy) and become root (or another user) for the tasks that need it, usually with sudo.

Common misunderstanding: "become_user: shop is the user Ansible logs in as." The docs: "become_user set to user with desired privileges — the user you become, NOT the user you login as." Also, "setting become_user does not set become": without become: true, become_user does nothing.

Definition: become: true turns escalation on (play, block or task level); become_method picks the plugin (sudo default, su, doas, runas on Windows...); become_user defaults to root; the same exist as connection variables (ansible_become, ansible_become_user). This chapter's plays template become: from the cm_manage_system switch, so the same playbook escalates on real hosts and not in the lab.

text
deploy@control$ ansible-playbook site.yml   (become: true, become_user: root; shape of -vvv output, not from this lab)
1  ssh deploy@orders-1
2  sudo -H -S -n -u root /bin/sh -c 'echo BECOME-SUCCESS-xyz; /usr/bin/python3 /home/deploy/.ansible/tmp/.../AnsiballZ_user.py'
3  module runs as root; result JSON back to the controller
   become_user: shop as an unprivileged target with pipelining off -> the temp file must be readable by shop
   (setfacl from the acl package, which is why the common role installs it)

Real scenarios:

  • A sudo rule deploy ALL=(ALL) NOPASSWD: ALL is convenient and means the deploy key is root on every host; narrow it, or use short-lived SSH certificates (Ansible in CI).
  • become_user: postgres for psql tasks fails with "Failed to set permissions on the temporary files" until acl is installed or pipelining is on.
  • become set globally in ansible.cfg makes every copy create root-owned files in the app's directory; set it per play.

Fix / how to use it: become per play or per task, never globally; --ask-become-pass (-K) for humans, NOPASSWD only for a CI identity that is itself short-lived.

Facts, gather_facts, the setup module; register, when, loop Must-know ​

In plain words: Before the first task, Ansible asks each host about itself (OS, IPs, memory, Python): those answers are facts. A task's result can be saved with register and used later in when conditions. loop repeats one task over a list.

Common misunderstanding: "when is evaluated once for the play." It is evaluated per host, per task (and per item inside a loop); a task can run on one host and be skipped on another in the same step. And Jinja2 braces are not used inside when: it is already an expression (when: kernel.stdout == 'Darwin').

Definition: "The setup module in Ansible automatically discovers a standard set of facts about each host"; gather_facts: false turns it off, gather_subset narrows it, and "Fact caching can improve performance." register: name stores the module's return value (for loops, name.results is a list with one entry per item). loop replaced most with_* forms; loop_control.label keeps output short.

yaml
# Facts, register, loop, when: the building blocks, against one lab host.
- name: Building blocks
  hosts: web1
  gather_facts: true
  gather_subset:
    - "!all"
    - "!min"
    - system
  tasks:
    - name: A few facts the setup module collected
      ansible.builtin.debug:
        msg: "system={{ ansible_facts['system'] }} python={{ ansible_facts['python_version'] }}"

    - name: Create one directory per environment (loop)
      ansible.builtin.file:
        path: "{{ cm_root }}/srv/{{ item }}"
        state: directory
        mode: "0755"
      loop:
        - staging
        - production
      register: dirs

    - name: Which loop items changed (register holds a results list)
      ansible.builtin.debug:
        msg: "{{ dirs.results | map(attribute='item') | zip(dirs.results | map(attribute='changed')) | list }}"

    - name: Read a value without changing anything
      ansible.builtin.command:
        cmd: uname -s
      register: kernel
      changed_when: false

    - name: Only on Linux (when)
      ansible.builtin.debug:
        msg: "this is Linux"
      when: kernel.stdout == 'Linux'

    - name: Only on macOS (when)
      ansible.builtin.debug:
        msg: "this is macOS, the lab controller"
      when: kernel.stdout == 'Darwin'
text
ran: playbooks/basics.yml against web1 (transcripts 48 and 49)
1  Gathering Facts (subset: system)                     ok
2  debug: system=Darwin python=3.9.6                    ok
3  file loop: staging, production                       changed, changed   (run 2: ok, ok)
4  debug of register results (item, changed) pairs      ok
5  command uname -s, changed_when: false                ok
6  when: kernel.stdout == 'Linux'                       skipping
7  when: kernel.stdout == 'Darwin'                      ok: "this is macOS, the lab controller"
   recap run 1: ok=5 changed=1 skipped=1   recap run 2: ok=5 changed=0 skipped=1

Real scenarios:

  • A role installs php8.4-fpm with ansible.builtin.package only when: ansible_facts['os_family'] == 'Debian', and a separate task for RedHat.
  • Fact gathering on 2,000 hosts takes minutes per run; gathering = smart plus a Redis fact cache with a 24-hour timeout cuts it to the first run of the day.
  • A registered command result is used in when under --check: the command was skipped in check mode, so the condition sees no stdout ("Check mode is just a simulation. It will not generate output for tasks that use conditionals based on registered variables").

Fix / how to use it: gather_facts: false for plays that do not need facts, a subset when you need a few, a cache for fleets; register only what you read; changed_when: false on read-only commands so they never report a change.

Variables and precedence: 22 levels, defaults vs vars, group merge order Must-know ​

In plain words: The same variable can be set in many places. Ansible picks the one from the most specific, most explicit place. You need to know about six of the 22 levels by heart.

Common misunderstanding: "Host vars always win." Play vars, role vars, task vars, set_fact and extra vars all beat inventory host vars. And for defaults vs vars in a role: defaults/ is the lowest level of all, vars/ is level 15 and beats every inventory variable.

Definition: the docs list precedence "from least to greatest (the last listed variables override all other variables)":

#Level#Level
1Command-line values (-u my_user; "these are not variables")12Play vars
2Role defaults (defaults/main.yml)13Play vars_prompt
3Inventory file or script group vars14Play vars_files
4Inventory group_vars/all15Role vars (vars/main.yml)
5Playbook group_vars/all16Block vars
6Inventory group_vars/*17Task vars
7Playbook group_vars/*18include_vars
8Inventory file or script host vars19Registered vars and set_fact
9Inventory host_vars/*20Role (and include_role) params
10Playbook host_vars/*21Include params
11Host facts and cached set_fact22Extra vars (-e), "always win precedence"

The docs' summary: "In general, Ansible gives precedence to variables that were defined more recently, more actively, and with more explicit scope." Footnote 1 matters for roles: "Tasks in each role see their own role's defaults. Tasks defined outside of a role see the last role's defaults."

A role on disk, and where its variables lose or winroles/go_service/defaults/main.ymlknobs, lowestvars/main.ymlconstants, hightasks/main.ymlentry pointtasks/system.ymlinclude_taskshandlers/main.ymlnotify targetstemplates/*.j2template modulefiles/copy module srcmeta/main.ymldependenciesmeta/argument_specs.ymlvalidates inputmolecule/default/testsRule of thumbdefaults: anything a caller may changevars: anything a caller must not changeinventory: per environment, group, hostPrecedence, lowest (top) to highest2 role defaults (1 = CLI values like -u)3-5 inventory vars, group_vars/all6-7 group_vars/<group> (same depth: alphabetical)8-10 host vars, host_vars/<host>11 facts and cached set_fact12-14 play vars, vars_prompt, vars_files15 role vars (vars/main.yml)16-18 block vars, task vars, include_vars19 set_fact and register20-21 role params, include params22 extra vars (-e): always winLab run: web1 = host_vars, web2 = group_vars/production(beats go_service), app1 = group_vars/all (beatsrole defaults); with -e every host says extra vars.
yaml
app_env: production
laravel_queue_workers: 4
# web2 is in go_service AND production: same depth, so the alphabetically
# later group (production) wins unless ansible_group_priority says otherwise.
demo_color: from group_vars/production
text
ran: playbooks/precedence.yml (transcripts 15 and 16); demo_color is defined in role defaults,
group_vars/all, group_vars/go_service, group_vars/production and host_vars/web1
1  web1 (go_service, staging)      -> "from host_vars/web1"           level 9 beats 6
2  web2 (go_service, production)   -> "from group_vars/production"    same depth: alphabetical, production > go_service
3  app1 (laravel, staging)         -> "from group_vars/all"           level 4 beats role defaults (2)
4  app2 (laravel, production)      -> "from group_vars/production"
5  -e demo_color=from-extra-vars   -> every host: "from-extra-vars"  level 22

Real scenarios:

  • A role sets nginx_worker_processes: 4 in vars/main.yml; ops set nginx_worker_processes: 16 in group_vars/web.yml and nothing happens. Move it to defaults/.
  • A host in eu and production gets ntp_server from whichever group sorts later; ansible_group_priority: 10 on eu makes the intent explicit.
  • A hotfix run with -e orders_api_version=1.4.3 deploys 1.4.3, and the next scheduled run without -e quietly rolls back to the inventory's 1.4.2. Extra vars are for one-offs; the release belongs in Git.

Fix / how to use it: callers' knobs in defaults/; internal constants in vars/; environment values in group_vars/<env>; host exceptions in host_vars; -e only for one-off runs; and ansible-inventory --host <name> (or debug: var=...) to see the merged answer.

Jinja2 templates and filters; template vs lineinfile vs blockinfile Must-know ​

In plain words: A template is a file with placeholders. The template module fills them in from variables on the control node and writes the result to the host, only if it differs from what is there. lineinfile and blockinfile edit a file in place instead of owning all of it.

Common misunderstanding: "lineinfile is the lightweight way to manage config." It is the fragile way: it owns one line and assumes the rest of the file stays as it was. The module's own docs point elsewhere: "See the ansible.builtin.replace module if you want to change multiple, similar lines or check ansible.builtin.blockinfile if you want to insert/update/remove a block of lines in a file. For other cases, see the ansible.builtin.copy or ansible.builtin.template modules." If you own the file, template it.

Definition: Ansible uses Jinja2 for every string with double braces (task arguments, when, templates). Templating happens on the controller: "Like all templating, lookups execute and are evaluated on the Ansible control machine." Filters transform values: default, mandatory, bool, int, to_nice_yaml, to_json, b64encode, urlencode, regex_replace, basename, dict2items, map(attribute=...), selectattr, sort(attribute=...), password_hash, ipaddr (ansible.utils). ansible_managed is a variable meant for a header comment saying the file is generated. The template module takes validate: ("A temporary file path is used to validate, passed in through %s which must be present") and backup: true.

jinja
# {{ ansible_managed }}
[Unit]
Description=orders-api {{ orders_api_version }}
Requires=orders-api.socket
After=network-online.target orders-api.socket
Wants=network-online.target

[Service]
Type=simple
User={{ orders_api_user }}
Group={{ orders_api_user }}
EnvironmentFile={{ orders_api_env_path }}
ExecStart={{ orders_api_install_dir }}/current/{{ orders_api_name }}
Restart=on-failure
RestartSec=2
# SIGTERM, then SIGKILL after this: the Go server drains in 20 s.
TimeoutStopSec=30
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes

[Install]
WantedBy=multi-user.target
jinja
# {{ ansible_managed }}
ORDERS_API_ADDR={{ orders_api_listen }}
ORDERS_API_ENV={{ app_env | default('production') }}
ORDERS_API_DB_DSN=postgres://orders:{{ orders_api_db_password | urlencode }}@{{ orders_api_db_host }}:5432/orders?sslmode=verify-full
text
template task, per host (what the module does)
1  controller: render orders-api.socket.j2 with this host's vars -> text T
2  controller: sha1(T); host: sha1(dest) via a stat call
3  equal      -> ok, nothing written, no handler
4  different  -> copy T to a temp file on the host, run validate (if set) on it, move into place atomically
5             -> changed; --diff prints before/after; notify queues the handler

Real scenarios:

  • sshd_config is templated with validate: /usr/sbin/sshd -t -f %s, so a typo never replaces the live file and locks everyone out.
  • A team uses lineinfile to set memory_limit in php.ini; a package upgrade ships a new php.ini with the line commented differently and the regex no longer matches, so a second line is appended.
  • A template containing a timestamp ({{ now() }} style) changes on every run and restarts the service on every run; the lab's units use ansible_managed without a date for this reason.
ModuleOwnsIdempotent whenUse for
ansible.builtin.templateThe whole fileRendered text is stableFiles you own: units, app config, vhosts
ansible.builtin.copyThe whole fileSource bytes are stableStatic files, binaries, content: one-liners
ansible.builtin.lineinfileOne line (by regexp)regexp matches what line writesOne setting in a distro file (/etc/sysctl.conf)
ansible.builtin.blockinfileA block between marker linesMarkers are uniqueA fragment in a file others also edit (/etc/hosts)
ansible.builtin.replaceEvery match of a regexThe replacement does not match the regex againBulk edits
community.general.ini_fileOne key in one INI sectionAlwaysINI files (php.ini, my.cnf)

Fix / how to use it: template whole files you own and add validate: where the program has a checker (sshd -t, visudo -cf, nginx -t -c for a full config, php-fpm8.4 -t -y for a pool as in the Laravel role); keep templates free of run-time values like dates; mark generated files with ansible_managed.

Idempotence: ok, changed, failed; command vs shell; creates; changed_when Must-know ​

In plain words: Idempotence means running the playbook twice in a row changes nothing the second time. Each task reports ok (already right), changed (made it right), failed, or skipped. A good playbook's second run says changed=0.

Common misunderstanding: "command is fine, it is just one line." The command module cannot know whether its command changed anything, so it reports changed every time, runs every time, and fires every handler it notifies. Its own docs: "while the command itself is arbitrary and cannot be subject to the check mode semantics it adds creates/removes options as a workaround".

Definition:

  • Real modules compare desired with actual state first (a file's checksum, a package's installed version, a user's UID) and act only on a difference. That comparison is the idempotence.
  • command vs shell: with command, "The command(s) will not be processed through the shell, so operations like "*", "<", ">", "|", ";" and "&" will not work." shell "is almost exactly like the ansible.builtin.command module but runs the command through a shell (/bin/sh) on the remote node." Prefer command (no injection through shell metacharacters), prefer a module over both.
  • creates / removes: "If a matching file already exists, this step will not be run" (creates; removes is the opposite). "Check mode is supported when passing creates or removes."
  • changed_when / failed_when: expressions over the registered result that decide the reported status, for example changed_when: "'Nothing to migrate' not in out.stdout".
text
ran: the first Laravel role draft (transcripts 05 and 06), second run, nothing changed in between
1  app1  Build the framework caches once per release   changed    <- creates: a path that never matched (see 38)
2  app1  Migrate the database once, from one host      changed    <- stand-in could not save its state, and run_once ran per batch
3  app2  Build the framework caches once per release   changed
4  app2  Migrate the database once, from one host      changed
   recap: app1 changed=2, app2 changed=2  -> not idempotent
isolated afterwards, each in a two-host playbook:
5  transcript 38: command + chdir + relative creates "sub/marker"   -> run 2 still changed (creates resolved inside chdir)
                  same task with creates "marker2"                  -> run 2 ok
6  transcript 37: serial: 1 + run_once                              -> runs on h1, then again on h2
                  when: inventory_hostname == ansible_play_hosts_all[0] -> h1 only, h2 skipping
ran: final role (transcripts 30 and 44): app1 ok=13 changed=0, app2 ok=12 changed=0, web1/web2 ok=11 changed=0

Real scenarios:

  • shell: curl -sL https://example.com/install.sh | bash runs the installer on every deploy, re-downloads a moving target, and cannot be checked. Use get_url with checksum: plus unarchive, or a package.
  • php artisan migrate --force reports changed every run, so a notify: restart queue workers restarts every worker on every deploy, even when no migration ran. changed_when on the "Nothing to migrate" line fixes the status (Laravel).
  • A command: useradd shop fails on the second run ("user already exists"); ansible.builtin.user is idempotent.
TaskRun 1Run 2Fix
ansible.builtin.file: state=directorychangedokNone needed
ansible.builtin.templatechangedokKeep templates stable
ansible.builtin.command: php artisan optimizechangedchangedcreates: <release>/bootstrap/cache/config.php (absolute; a relative path is resolved inside chdir)
ansible.builtin.command: php artisan migrate --forcechangedchangedchanged_when on the output
ansible.builtin.command: uname -s (read-only)changedchangedchanged_when: false
ansible.builtin.shell: apt-get install -y nginxchangedchangedansible.builtin.apt: name=nginx state=present
ansible.builtin.copy: content="{{ now() }}" stylechangedchangedDo not template run-time values
block + rescue that writes v2 then v1 backchangedchangedValidate a candidate before touching the live file (see Error handling)

Fix / how to use it: run every playbook twice in CI or Molecule (its idempotence step fails on any change in the second converge); treat a changed on the second run as a bug; for each remaining command, add creates, removes or changed_when, and changed_when: false on read-only ones.

Handlers, notify, listen and flush_handlers Must-know ​

In plain words: A handler is a task that runs only if another task changed something and notified it. It runs once, at the end of the section, however many tasks notified it. That is how "restart the service if its config changed" is written.

Common misunderstanding: "Handlers run in the order I notify them." The docs: "Handlers are executed in the order they are defined in the handlers section, not in the order listed in the notify statement." Second one: "If the play fails, the handler still runs." No: a host that fails a task does not run its pending handlers, unless force_handlers: true.

Definition: "Handlers are tasks that only run when notified." "Notifying the same handler multiple times will result in executing the handler only once regardless of how many tasks notify it." listen: lets several handlers share a topic ("Notifying the restart web services topic results in executing all handlers listening to that topic regardless of how those handlers are named"). "By default, handlers run after all the tasks in a particular play have been completed. Notified handlers are executed automatically after each of the following sections, in the following order: pre_tasks, roles/tasks and post_tasks." meta: flush_handlers runs them earlier; the Go role does that before its health check.

One play: batches, tasks across hosts, the handler queue, the recaphosts: go_serviceserial: [1, "50%"]batch 1: web1batch 2: web2one batch at a timeInside a batch (strategy: linear)gather_facts (setup module)pre_tasks then flush handlersroles: common (meta dependency), go_servicetask 1 on every host of the batchtask 2 on every host ... (free: no waiting)tasks then flush handlerspost_tasks then flush handlersper host, per task: ok | changed | failed | skippedHandler queuechanged + notify:"orders-api restart"listen topics fan outto several handlersnotified 3 times,runs onceorder = definitionorder, not notify orderflush: end of each section or meta: flush_handlersWhen a task fails on a hosthost leaves the play (unless block/rescue catches it)its queued handlers do not run (see force_handlers)max_fail_percentage: 0: later batches never startany_errors_fatal: stop every host nowPLAY RECAP (per host)ok=11 changed=0 unreachable=0 failed=0skipped=5 rescued=0 ignored=0second run with changed=0 everywhere= the playbook is idempotent
yaml
# Handlers run once, at the end of the play section (or at meta: flush_handlers),
# in the order they are written here, not in the order they were notified.
- name: Reload systemd units
  ansible.builtin.systemd_service:
    daemon_reload: true
  when: cm_manage_system | bool
  listen: orders-api unit changed

- name: Restart orders-api
  ansible.builtin.systemd_service:
    name: orders-api.service
    state: restarted
  when: cm_manage_system | bool
  listen:
    - orders-api unit changed
    - orders-api restart

- name: Restart orders-api (local stand-in, no systemd in the lab)
  ansible.builtin.debug:
    msg: "stand-in: systemctl restart orders-api.service on {{ inventory_hostname }}"
  when: not (cm_manage_system | bool)
  listen:
    - orders-api unit changed
    - orders-api restart
text
ran: --tags config --limit web1 --diff -e orders_api_port=8081 (transcript 11)
1  Environment file from Vault variables     changed   notify: orders-api restart      (diff suppressed: diff: false)
2  systemd socket and service units          changed (orders-api.socket), ok (orders-api.service)
                                                       notify: orders-api unit changed
3  end of roles section: handler queue = {Reload systemd units, Restart orders-api, Restart (stand-in)}
4  RUNNING HANDLER Reload systemd units      skipping  (when: cm_manage_system, false in the lab)
5  RUNNING HANDLER Restart orders-api        skipping
6  RUNNING HANDLER Restart (local stand-in)  ok: "stand-in: systemctl restart orders-api.service on web1"
   two notifications, one restart; reload runs before restart because it is defined first

Real scenarios:

  • A unit file and its env file both change; daemon-reload must happen before restart, or systemd restarts the old unit definition. Defining the reload handler first (and listening on the same topic) guarantees the order.
  • A task after the config change fails on host 3; the restart handler never runs there, so host 3 keeps the old process with the new config on disk. The next run's template is ok, so nothing notifies the handler again. force_handlers: true or an explicit restart in rescue closes the gap.
  • A health check after a restart must see the new process: meta: flush_handlers before the uri task.
FeatureAnsiblePuppetChefSalt
Restart on changenotify + handlernotify / ~> (refresh)notifies :restart, ..., :delayedwatch: / onchanges:
Runs once per runYesYes (one refresh per resource):delayed queues onceYes
Run nowmeta: flush_handlers(graph order):immediatelylisten / requisites

Fix / how to use it: every restart and reload is a handler; reload before restart in the handler file; flush_handlers before verification; force_handlers: true on plays where a half-applied config is dangerous.

Check mode (--check) and diff mode (--diff) Important ​

In plain words: --check runs the playbook without changing anything and says what it would change. --diff shows the changed lines of files. Together they are the review step before a real run, and the way to see drift.

Common misunderstanding: "If --check passes, the real run will pass." "Check mode is just a simulation." Tasks that depend on something an earlier task would have created (a directory, a symlink target, a release checkout) can fail in check mode and succeed for real, and the reverse. The lab hit exactly this three times on an empty host.

Definition: "In check mode, Ansible runs without making any changes on remote systems. Modules that support check mode report the changes they would have made." check_mode: true|false on a task forces the mode; the magic variable ansible_check_mode is true during --check. Diff mode prints before/after for modules that support it; diff: false on a task suppresses it (use it on every task that renders a secret).

text
ran: site.yml --check --diff on an EMPTY lab tree (transcripts 01-04)
1  run 01: go_service "Point current at the new release" FAILED
           "src file does not exist, use "force=yes" if you really want to create the link"
           -> serial batch 1 failed, max_fail_percentage 0 -> NO MORE HOSTS LEFT (web2 and Laravel never ran)
   fix: force: "{{ ansible_check_mode }}" on the symlink task
2  run 02: laravel_app "php artisan optimize" FAILED "Unable to change directory before execution"
   fix: when: not ansible_check_mode on the artisan tasks
3  run 03: handler "Rebuild Laravel caches" FAILED (chdir into current, which --check did not create)
   fix: when: not ansible_check_mode on the two artisan handlers
4  run 04: exit 0, changed=7 (web) / changed=10 (app); runs 07 and 42 on a fresh root: same, and the lab tree still does not exist afterwards
yaml
- name: Service account and root-owned config directory (real hosts only)
  ansible.builtin.include_tasks: system.yml
  when: cm_manage_system | bool
  tags: [system]

- name: Release layout
  ansible.builtin.file:
    path: "{{ orders_api_home }}/{{ item }}"
    state: directory
    mode: "0755"
  loop:
    - releases
    - "releases/{{ orders_api_version }}"
  tags: [release]

- name: Config directory
  ansible.builtin.file:
    path: "{{ cm_root }}/etc/orders-api"
    state: directory
    mode: "0750"
    owner: "{{ 'root' if cm_manage_system | bool else omit }}"
    group: "{{ orders_api_user if cm_manage_system | bool else omit }}"
  tags: [config]

- name: Fetch the release binary (checksummed)
  ansible.builtin.get_url:
    url: "{{ orders_api_artifact_url }}"
    dest: "{{ orders_api_home }}/releases/{{ orders_api_version }}/{{ orders_api_name }}"
    checksum: "sha256:{{ orders_api_sha256 }}"
    mode: "0755"
  when: orders_api_local_binary is not defined
  tags: [release]

- name: Copy the release binary built on the controller (local lab)
  ansible.builtin.copy:
    src: "{{ orders_api_local_binary }}"
    dest: "{{ orders_api_home }}/releases/{{ orders_api_version }}/{{ orders_api_name }}"
    mode: "0755"
  when: orders_api_local_binary is defined
  tags: [release]

- name: Environment file from Vault variables
  ansible.builtin.template:
    src: orders-api.env.j2
    dest: "{{ cm_root }}{{ orders_api_env_path }}"
    mode: "0640"
    owner: "{{ 'root' if cm_manage_system | bool else omit }}"
    group: "{{ orders_api_user if cm_manage_system | bool else omit }}"
  diff: false          # --diff would print the password
  notify: orders-api restart
  tags: [config]

- name: systemd socket and service units
  ansible.builtin.template:
    src: "{{ item }}.j2"
    dest: "{{ cm_root }}/etc/systemd/system/{{ item }}"
    mode: "0644"
  loop:
    - orders-api.socket
    - orders-api.service
  notify: orders-api unit changed
  tags: [config]

- name: Point current at the new release
  ansible.builtin.file:
    src: "releases/{{ orders_api_version }}"   # relative link: valid on the host and in the lab
    dest: "{{ orders_api_home }}/current"
    state: link
    # In --check on a fresh host the release directory does not exist yet;
    # without this the dry run fails on a task that would succeed for real.
    force: "{{ ansible_check_mode }}"
  notify: orders-api restart
  tags: [release]

- name: Find old releases
  ansible.builtin.find:
    paths: "{{ orders_api_home }}/releases"
    file_type: directory
  register: orders_api_releases
  tags: [release]

- name: Remove all but the newest releases
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ (orders_api_releases.files | sort(attribute='mtime'))[:-orders_api_keep_releases] }}"
  loop_control:
    label: "{{ item.path | basename }}"
  when: item.path | basename != orders_api_version
  tags: [release]

- name: Start, enable and health-check (real hosts only)
  ansible.builtin.include_tasks: service.yml
  when: cm_manage_system | bool
  tags: [system]

Real scenarios:

  • A nightly --check --diff against production prints a diff for one host's Nginx site: somebody hot-fixed it by hand. The diff is the drift report.
  • --check on a host where the package is not installed yet: the template task for the package's config directory fails because the directory does not exist. Same class of failure as the lab's.
  • A --diff run of a task that renders .env prints DB_PASSWORD=... into the CI log. diff: false (used in both roles) or no_log: true prevents it.

Fix / how to use it: make check mode a supported path: guard tasks that cannot predict with when: not ansible_check_mode or a check-mode-friendly argument, run --check --diff in CI before every apply, and read the diff.

Tags, --tags and --limit Important ​

In plain words: Tags label tasks so you can run only some of them (--tags config). --limit runs the playbook on only some hosts (--limit web1).

Common misunderstanding: "Tagging a role's tasks lets me skip everything else safely." Untagged dependencies, facts and handlers interact: the docs warn that "Setting a tag on a task in a block but not in the rescue or always section will prevent those from triggering if your tags selection does not cover the tasks in those sections". And --tags on an include_tasks selects only the include unless you use apply: tags.

Definition: "The tags keyword always defines tags and adds them to tasks; it does not select or skip tasks for execution." Selection is --tags, --skip-tags; special tags always (runs unless skipped explicitly) and never (runs only if selected). --limit takes a host pattern (web1, go_service:&production, !app2, @retry_file). --list-tasks and --list-tags print what would run.

bash
# ran (transcript 25): what tags exist and which tasks they select
$ ansible-playbook playbooks/site.yml --list-tasks --list-tags
#      TASK TAGS: [always, config, layout, release, system]      (play 1, Go service)
#      TASK TAGS: [config, layout, migrate, release, system]     (play 2, Laravel)
# ran (transcript 11): only config tasks, only web1
$ ansible-playbook playbooks/site.yml --tags config --limit web1 --diff -e orders_api_port=8081
# web1 : ok=7 changed=2 unreachable=0 failed=0 skipped=2

Real scenarios:

  • A config-only hotfix (--tags config) to 30 hosts finishes in a minute because releases, packages and users are skipped.
  • --limit orders-1.prod is the canary step done by hand; serial: [1, ...] is the same idea automated.
  • The always tag on the load-balancer drain and enable tasks in site.yml keeps a --tags config run from restarting a host that is still in rotation.

Fix / how to use it: a small fixed vocabulary of tags per repository (system, layout, release, config, migrate), always on safety steps (drain, enable), and --list-tasks in code review for any tag-selected run.

serial, rolling updates, strategy and the free strategy Important ​

In plain words: serial makes Ansible finish the whole play on a few hosts before starting the next few: a rolling update. The strategy decides whether hosts wait for each other at every task (linear) or run ahead (free).

Common misunderstanding: "serial makes each task run one host at a time." It makes the play run per batch; within a batch, tasks still run on all hosts of the batch in parallel. And run_once inside a serial play means once per batch: in transcript 37 a run_once task in a serial: 1 play ran on h1 and then again on h2.

Definition: "By default, Ansible runs each task on all hosts affected by a play before starting the next task on any host, using 5 forks." "The default behavior described above is the linear strategy. Ansible offers other strategies, including the debug strategy ... and the free strategy, which allows each host to run until the end of the play as fast as it can". serial accepts a number, a percentage or a list ("Ansible completes the play on the specified number or percentage of hosts before starting the next batch of hosts"). "Setting the batch size with serial changes the scope of the Ansible failures to the batch size, not the entire host list. You can use ignore_unreachable or max_fail_percentage to modify this behavior." throttle limits workers for one task; order (inventory, sorted, shuffle...) sorts hosts; run_once runs a task on the first host of the batch.

text
ran: site.yml play 1, serial [1, "50%"], max_fail_percentage 0 (transcripts 08 and 01)
normal run:
1  batch 1 [web1]: drain -> roles -> handlers -> enable
2  batch 2 [web2]: drain -> roles -> handlers -> enable
failing run (01, check mode on an empty tree):
1  batch 1 [web1]: task "Point current at the new release" FAILED
2  failed hosts 1/1 = 100% > 0%  -> "NO MORE HOSTS LEFT", batch 2 never starts, play 2 never starts
   that is the canary doing its job: one host broken, the rest untouched

Real scenarios:

  • 12 web servers behind a load balancer: serial: [1, "25%", "100%"] gives a canary, then quarters, then the rest; max_fail_percentage: 0 stops at the canary.
  • A package mirror update across 500 hosts with no ordering needs: strategy: free and forks: 100 let fast hosts finish without waiting for slow ones.
  • A cache warm-up endpoint that can take one request at a time: throttle: 1 on that task only.
KeywordScopeDefaultEffect
forksConfig / CLI -f5Parallel hosts per task
serialPlayAll hostsBatches; failures counted per batch
max_fail_percentagePlay(100)Abort when exceeded within a batch
any_errors_fatalPlay / blockfalseAny failure stops every host
strategyPlay / configlinearfree, debug, host_pinned
throttleTask / blockforksMax workers for that task
run_onceTaskfalseFirst host of the batch; result applied to all
orderPlayinventoryHost order within the play

Fix / how to use it: serial with a canary batch and max_fail_percentage: 0 on every play that restarts services; drain and re-enable in pre_tasks/post_tasks with the always tag; one-time steps (migrations) bound to ansible_play_hosts_all[0], not run_once, when the play is batched.

Error handling: block rescue always, failed_when, changed_when, ignore_errors Important ​

In plain words: block groups tasks; rescue runs if one of them fails; always runs either way. failed_when says what failure means for a command; ignore_errors lets a failure pass but still shows it.

Common misunderstanding: "ignore_errors makes Ansible keep going no matter what." The docs: "The ignore_errors directive only works when the task can run and returns a value of 'failed'. It does not make Ansible ignore undefined variable errors, connection failures, execution issues (for example, missing packages), or syntax errors." Likewise for blocks: "Errors caused by invalid task definitions and unreachable hosts do not trigger the rescue or always sections of a block."

Definition: "Rescue blocks specify tasks to run when an earlier task in a block fails. This approach is similar to exception handling in many programming languages. Ansible only runs rescue blocks after a task returns a 'failed' state." Inside rescue, ansible_failed_task and ansible_failed_result describe the failure. "Ansible lets you define what 'failure' means in each task using the failed_when conditional", and lists of conditions are joined with "an implicit and".

yaml
# block / rescue / always, failed_when, changed_when, ignore_errors.
# Validate first, write second: the candidate is checked before the live file
# is touched, and rescue only ensures the known-good version, so a second run
# reports changed=0 (an earlier version wrote v2 then rolled back to v1 on
# every run: changed=2 forever).
- name: Error handling
  hosts: web1
  gather_facts: false
  tasks:
    - name: Deploy a new config only if it validates
      block:
        - name: Write the candidate next to the live file
          ansible.builtin.copy:
            dest: "{{ cm_root }}/errors-demo.conf.candidate"
            content: "version=2\n"
            mode: "0644"

        - name: Validate the candidate (this one fails, like a migration that cannot apply)
          ansible.builtin.command:
            cmd: /bin/sh -c 'echo "ERROR - column total_cents exists" >&2; exit 3'
          register: migration
          changed_when: false

        - name: Promote the candidate (never reached in this demo)
          ansible.builtin.copy:
            src: "{{ cm_root }}/errors-demo.conf.candidate"
            dest: "{{ cm_root }}/errors-demo.conf"
            remote_src: true
            mode: "0644"

      rescue:
        - name: Make sure the known-good config is live
          ansible.builtin.copy:
            dest: "{{ cm_root }}/errors-demo.conf"
            content: "version=1\n"
            mode: "0644"

        - name: Say what failed
          ansible.builtin.debug:
            msg: "rescued: {{ ansible_failed_task.name }} rc={{ ansible_failed_result.rc }}"

      always:
        - name: Runs whatever happened
          ansible.builtin.debug:
            msg: "always: release lock"

    - name: grep exits 1 when nothing matches; that is not a failure
      ansible.builtin.command:
        cmd: grep -c TODO {{ cm_root }}/errors-demo.conf
      register: todo
      failed_when: todo.rc not in [0, 1]
      changed_when: false

    - name: A check whose failure we accept (and see in the recap)
      ansible.builtin.command:
        cmd: "false"   # found on PATH: /bin/false on Linux, /usr/bin/false on macOS
      ignore_errors: true
      changed_when: false
text
ran: playbooks/errors.yml, twice (transcripts 46 and 47)
1  block   Write the candidate next to the live file   changed (run 2: ok)
2  block   Validate the candidate                      FAILED   rc=3, stderr "ERROR - column total_cents exists"
3  block   Promote the candidate                       never reached
4  rescue  Make sure the known-good config is live     changed (run 2: ok)
5  rescue  Say what failed                             ok: "rescued: Validate the candidate (this one fails, like a migration that cannot apply) rc=3"
6  always  Runs whatever happened                      ok: "always: release lock"
7  grep -c TODO (rc 1 = no match)                      ok       failed_when: todo.rc not in [0, 1]
8  "false" with ignore_errors                          FAILED ...ignoring
   run 1: ok=6 changed=2 rescued=1 ignored=1      run 2: ok=6 changed=0 rescued=1 ignored=1
   the first version wrote version=2 into the live file and rescued back to version=1: changed=2 on EVERY run (transcripts 35, 36)

Real scenarios:

  • A deploy writes the new config, the smoke test fails, rescue restores the previous current symlink and notifies a restart: an automated rollback per host.
  • grep, diff and systemctl is-active use exit codes that are not errors (1 = no match, 3 = inactive); failed_when: result.rc not in [0, 1] encodes that.
  • A lock is taken at the start (a marker file, a load-balancer flag); always releases it whatever happened.

Fix / how to use it: block/rescue for rollbacks that you can actually perform, always for cleanup, failed_when instead of ignore_errors whenever you can say what success looks like, and ignore_errors only on purpose (it still shows up as ignored= in the recap). The lab shows why the order matters: the first version of this playbook wrote the new file and let rescue write the old one back, which reported changed=2 on every run (a flip that Molecule's idempotence step would flag); writing a candidate, validating it, and only then promoting it gives changed=0 on the second run.

Roles: role layout, defaults vs vars, meta dependencies, argument specs, ansible-galaxy Must-know ​

In plain words: A role is a folder with a fixed layout (tasks, handlers, templates, defaults...) that you can reuse in any play by name. It is the unit you test, version and share.

Common misunderstanding: "Role dependencies run every time they are listed." A dependency in meta/main.yml runs once per play, before the role that needs it, even if several roles list it (unless it allows duplicates); in the lab, common ran once per host although both application roles depend on it.

Definition: the role layout (tasks/main.yml, handlers/main.yml, defaults/main.yml, vars/main.yml, files/, templates/, meta/main.yml, meta/argument_specs.yml, plus library/, module_utils/, lookup_plugins/ for custom plugins). Roles are used with roles: (static, at the start of the play), import_role (static, inline) or include_role (dynamic, can loop and take when). meta/argument_specs.yml validates a role's input before its tasks run (the lab's "Validating arguments against arg spec 'main'" task). ansible-galaxy role init scaffolds one; ansible-galaxy collection install and role install fetch from Galaxy or Git.

yaml
# Role defaults: the knobs callers are expected to override.
orders_api_version: "0.0.0"
orders_api_port: 8080
orders_api_listen: "127.0.0.1:{{ orders_api_port }}"
orders_api_keep_releases: 3
orders_api_health_retries: 15
# Production fetches a checksummed artifact; the local lab copies a binary
# built on the controller (set orders_api_local_binary).
orders_api_artifact_url: "https://artifacts.example.com/orders-api/{{ orders_api_version }}/orders-api-linux-amd64"
orders_api_sha256: ""
orders_api_db_host: db.internal
orders_api_db_password: ""   # always set from a vault_ variable in inventory
yaml
# Role vars: internal constants. They beat inventory and play vars, so do not
# put anything here that a caller should be able to change.
orders_api_name: orders-api
orders_api_user: orders-api
orders_api_install_dir: /opt/orders-api            # path on the real host
orders_api_env_path: /etc/orders-api/orders-api.env
orders_api_home: "{{ cm_root }}{{ orders_api_install_dir }}"   # where files are written
yaml
galaxy_info:
  author: academy
  description: Deploy the orders-api Go binary as a socket-activated systemd service
  license: MIT
  min_ansible_version: "2.15"
  platforms:
    - name: Ubuntu
      versions: [noble]
# Runs once per play before this role, however many roles depend on it.
dependencies:
  - role: common
yaml
# Validated before the role's tasks run (ansible-core 2.11+): a typo in a
# caller's variable fails the play instead of deploying the default.
argument_specs:
  main:
    short_description: Deploy orders-api
    options:
      orders_api_version:
        type: str
        required: true
      orders_api_port:
        type: int
        default: 8080
      orders_api_keep_releases:
        type: int
        default: 3
      orders_api_db_password:
        type: str
        required: true
        no_log: true
yaml
- name: Base packages and timezone (real hosts only)
  ansible.builtin.include_tasks: system.yml
  when: cm_manage_system | bool
  tags: [system]

- name: Base directory layout
  ansible.builtin.file:
    path: "{{ cm_root }}{{ item }}"
    state: directory
    mode: "0755"
  loop:
    - /etc
    - /opt
    - /var/log
    - /etc/systemd/system
  tags: [layout]
text
roles: [go_service] in a play, per host
1  meta/main.yml dependencies -> common (once per play)
2  common: defaults, tasks (layout; system.yml via include_tasks only when cm_manage_system)
3  go_service: argument_specs validated -> "Validating arguments against arg spec 'main'"
4  go_service: tasks/main.yml in order; notify into go_service handlers
5  end of the roles section -> handlers flushed

Real scenarios:

  • Three teams copy the same 200-line "install nginx" task list into their playbooks; one role with defaults for ports and worker counts replaces all three.
  • A caller passes orders_api_verison (typo): without argument specs the role silently deploys the default 0.0.0; with them, the play fails before any task.
  • include_role with loop deploys five similar services from one role, each with its own variables.
Folder / filePurposePrecedence of vars there
defaults/main.ymlKnobs a caller may overrideLevel 2 (lowest that is a variable)
vars/main.ymlInternal constantsLevel 15 (beats inventory and play vars)
tasks/main.ymlEntry point; include_tasks/import_tasks for the rest-
handlers/main.ymlNotified tasks-
templates/.j2 files for the template module-
files/Static files for the copy module-
meta/main.ymlgalaxy_info, dependencies-
meta/argument_specs.ymlInput validation (ansible-core 2.11+)-
molecule/<scenario>/Tests-

Fix / how to use it: one role per service, defaults for every knob, argument specs for required inputs, dependencies only for real prerequisites, and roles published as part of a collection (namespace.collection.role) once more than one repository uses them.

Secrets: Ansible Vault, ansible-vault encrypt, vault IDs, encrypt_string; SOPS and lookup plugins Must-know ​

In plain words: Ansible Vault encrypts a variables file (or a single value) with a password, so it can live in Git. At run time you give Ansible the password and it decrypts in memory. Vault IDs label which password a piece of content needs.

Common misunderstanding: "Encrypted in Git means safe." The docs' warning: "Encryption with Ansible Vault ONLY protects 'data at rest'." Once a run decrypts a value, --diff, -v, a debug task, a failed task's error message, or ansible-inventory --list with the password all print it (the lab's inventory check shows the decrypted vault_* values). Protect the run, too: no_log: true, diff: false, and CI logs that are not public.

Definition:

  • ansible-vault create|encrypt|decrypt|edit|view|rekey <file> on whole files; ansible-vault encrypt_string on one value: "The ansible-vault encrypt_string command encrypts and formats any string you type (or copy or generate) into a format that can be included in a playbook, role, or variables file."
  • Vault ID: --vault-id label@source, where source is a prompt, a file or a script; "Encrypted content created with --vault-id also contains the vault ID label" (the header becomes $ANSIBLE_VAULT;1.2;AES256;demo). Several IDs can be passed in one run (dev@..., prod@...).
  • Password client scripts: "If you store your passwords in a third-party tool, you need a vault password client script to retrieve them from within Ansible." An executable password file is run and its stdout is the password.
  • The indirection pattern (Ansible tips): put secrets in group_vars/<group>/vault.yml as vault_db_password, and reference them from a plain vars.yml as db_password: "{{ vault_db_password }}", so grep still finds every variable name.
  • Alternatives: SOPS ("SOPS is an editor of encrypted files that supports YAML, JSON, ENV, INI and BINARY formats and encrypts with AWS KMS, GCP KMS, Azure Key Vault, HuaweiCloud KMS, age, and PGP") through the community.sops collection (a vars plugin and the load_vars module); lookup plugins that fetch at run time, such as community.hashi_vault.hashi_vault, amazon.aws.aws_secret and ansible.builtin.env.
yaml
orders_api_version: "1.4.2"
orders_api_port: 8080
orders_api_db_password: "{{ vault_orders_api_db_password }}"
demo_color: from group_vars/go_service
bash
#!/usr/bin/env bash
# Vault password client for CI: Ansible runs an EXECUTABLE --vault-password-file
# and reads the password from its stdout, so the password never touches disk.
#   ANSIBLE_VAULT_PASSWORD=... ansible-playbook --vault-id prod@scripts/vault-pass-from-env.sh ...
set -euo pipefail
: "${ANSIBLE_VAULT_PASSWORD:?ANSIBLE_VAULT_PASSWORD is not set}"
printf '%s\n' "$ANSIBLE_VAULT_PASSWORD"
bash
# ran (transcript 23): the vault file in Git, decrypting it, a wrong password, a missing one
$ head -c 120 ansible/inventories/local/group_vars/all/vault.yml
$ANSIBLE_VAULT;1.2;AES256;demo
38383762666364663039643432366637643131313565393665303832363663623134393337613464
$ ansible-vault view --vault-id demo@wrong-pass.txt .../group_vars/all/vault.yml
ERROR! Decryption failed (no vault secrets were found that could decrypt) on .../vault.yml for .../vault.yml
$ ansible-playbook kb/ansible/playbooks/precedence.yml          # no --vault-id at all
ERROR! Attempting to decrypt but no vault secrets found                                   (exit 4)
$ ansible-vault encrypt_string --vault-id demo@demo-vault-password.txt --name vault_redis_password lab-only-redis-pw
vault_redis_password: !vault |
          $ANSIBLE_VAULT;1.2;AES256;demo
          63626239353836353530393135346232633365643632376633333034626564323065313935613263
          ...

The lab's vault password is a throwaway file (demo-vault-password.txt, content throwaway-demo-password-not-a-secret) committed on purpose so the lab is reproducible; every value inside is fake. A real repository never contains the password, only the encrypted file.

Real scenarios:

  • A developer leaves --diff on in a CI job that templates .env; the database password is in the build log for 90 days. diff: false on the task (as in both roles here) prevents it.
  • Rotating the vault password: ansible-vault rekey --vault-id old@... --new-vault-id prod@... on every encrypted file, then update the secret store that the password client script reads.
  • A team on AWS keeps secrets in Secrets Manager and uses the lookup plugin at run time; nothing secret is in Git at all, and rotation needs no commit.
OptionWhere the secret livesDecrypted byGood forCost
Ansible Vault filesGit, encrypted with a passwordansible-coreSmall teams, no external dependencyOne shared password to distribute and rotate
encrypt_string valuesGit, inline !vaultansible-coreOne secret in an otherwise plain fileHarder to diff and rotate
SOPS + community.sopsGit, encrypted per value with KMS/agesops binary + cloud KMSPer-environment keys, IAM-controlled decryptionKMS setup
Lookup plugins (HashiCorp Vault, AWS Secrets Manager)External storeThe lookup, at run time, on the controllerRotation, audit, no secret in GitNetwork dependency during runs
CI secret / OIDC-fetchedCI or external storeThe pipelineVault password itselfPipeline identity setup

Fix / how to use it: vault files with the vault_ indirection, one vault ID per environment, the password delivered by a client script from a secret store (the CI workflow reads it from HashiCorp Vault with OIDC), and no_log/diff: false on every task that handles a secret. Kubernetes secrets are a different problem with different tools: Kubernetes Config, Secrets & Storage.

Testing: --syntax-check, ansible-lint, Molecule, the assert module Important ​

In plain words: Four layers: does it parse (--syntax-check), does it follow the rules (ansible-lint), does it work and stay idempotent on a fresh machine (Molecule), and is the result what you meant (assert and stat checks on the end state).

Common misunderstanding: "--syntax-check tests my playbook." It parses YAML, resolves static imports and roles and checks module names; it does not run anything, evaluate when, or load dynamically included files (include_tasks content is not checked). The lab's system.yml files, which use community.general and ansible.builtin.apt, are only reachable through include_tasks, so syntax-check would not notice a typo in them.

Definition:

  • ansible-playbook --syntax-check (ran on every playbook here, transcript 25).
  • ansible-lint with profiles: "The min profile ensures that Ansible can load content"; "The basic profile prevents common coding issues and enforces standard styles and formatting" (it includes no-free-form, name, yaml, var-naming...); then moderate, safety, shared, production. Configured in .ansible-lint; "List values such as skip_list, warn_list, and exclude_paths are extended (appended to), not replaced."
  • Molecule: "Molecule is an Ansible testing framework designed for developing and testing Ansible collections, playbooks, and roles"; a scenario's default test_sequence is "dependency - cleanup - destroy - syntax - create - prepare - converge - idempotence - side_effect - verify - cleanup - destroy". "The create/destroy playbooks for Docker and Podman are bundled with Molecule."
  • assert module: "This module asserts that given expressions are true with an optional custom message"; that: takes the same expressions as when.
yaml
# ansible-lint configuration (expected, not run: ansible-lint is not installed
# in the build environment; CI installs it, see github/ansible.yml).
# "production" is the strictest profile: it includes min, basic, moderate,
# safety and shared, and checks FQCNs, names, risky permissions, no
# changed_when-less commands, and more.
profile: production
exclude_paths:
  - collections/
  - .ansible-facts/
  - roles/*/molecule/
# Rules we enforce on top of the profile.
enable_list:
  - no-same-owner
# Never silence a rule globally to get green; use a "# noqa: rule" comment on
# the one line, with a reason, so reviewers see it.
skip_list: []
offline: false
yaml
# Molecule scenario for the go_service role (expected, not run: no Docker in
# the build environment). Needs: pip install molecule "molecule-plugins[docker]".
#   cd roles/go_service && ORDERS_API_BINARY=/path/to/orders-api molecule test
dependency:
  name: galaxy
  options:
    requirements-file: ../../requirements.yml
driver:
  name: docker
platforms:
  # An image with systemd as PID 1, so the role's systemd tasks are real.
  - name: orders-api-noble
    image: geerlingguy/docker-ubuntu2404-ansible:latest
    pre_build_image: true
    command: ""
    privileged: true
    cgroupns_mode: host
    volumes:
      - /sys/fs/cgroup:/sys/fs/cgroup:rw
    groups:
      - go_service
provisioner:
  name: ansible
  inventory:
    group_vars:
      go_service:
        cm_manage_system: true
        cm_root: ""
        orders_api_version: "1.4.2"
        orders_api_db_password: molecule-only-not-a-secret
        orders_api_local_binary: "${ORDERS_API_BINARY}"
verifier:
  name: ansible
scenario:
  # The default sequence minus side_effect/cleanup: converge twice
  # (idempotence fails the run if the second pass reports any change).
  test_sequence:
    - dependency
    - destroy
    - syntax
    - create
    - prepare
    - converge
    - idempotence
    - verify
    - destroy
yaml
- name: Verify
  hosts: go_service
  become: true
  gather_facts: false
  tasks:
    - name: Collect systemd unit states
      ansible.builtin.service_facts:

    - name: Socket and service are running
      ansible.builtin.assert:
        that:
          - ansible_facts.services['orders-api.service'].state == 'running'
          - ansible_facts.services['orders-api.service'].status == 'enabled'

    - name: Health endpoint answers with the deployed version
      ansible.builtin.uri:
        url: http://127.0.0.1:8080/healthz
        return_content: true
      register: health
      failed_when: health.json.version != '1.4.2'

    - name: The env file is not world-readable
      ansible.builtin.stat:
        path: /etc/orders-api/orders-api.env
      register: envfile
      failed_when: envfile.stat.mode != '0640' or envfile.stat.pw_name != 'root'
yaml
# Molecule-style verify against the lab trees: assert the end state, not the steps.
- name: Verify the Go service layout
  hosts: go_service
  gather_facts: false
  tasks:
    - name: Stat the deployed files
      ansible.builtin.stat:
        path: "{{ cm_root }}{{ item }}"
      loop:
        - /opt/orders-api/current/orders-api
        - /etc/orders-api/orders-api.env
        - /etc/systemd/system/orders-api.service
        - /etc/systemd/system/orders-api.socket
      register: st

    - name: Files exist, binary is executable, env file is not world-readable
      ansible.builtin.assert:
        that:
          - st.results | map(attribute='stat.exists') | min
          - st.results[0].stat.executable
          - st.results[1].stat.mode == '0640'
        quiet: true

    - name: current points at the inventory version
      ansible.builtin.stat:
        path: "{{ cm_root }}/opt/orders-api/current"
      register: cur

    - name: Symlink target
      ansible.builtin.assert:
        that:
          - cur.stat.islnk
          - cur.stat.lnk_source | basename == orders_api_version
        quiet: true

- name: Verify the Laravel layout
  hosts: laravel
  gather_facts: false
  tasks:
    - name: Rendered queue worker unit names the worker count's connection
      ansible.builtin.command:
        cmd: grep -c "queue:work redis" {{ cm_root }}/etc/systemd/system/shop-queue@.service
      register: unit
      changed_when: false

    - name: Release has its shared .env and caches
      ansible.builtin.stat:
        path: "{{ cm_root }}/var/www/shop/current/{{ item }}"
      loop:
        - .env
        - bootstrap/cache/config.php
      register: rel

    - name: Assert
      ansible.builtin.assert:
        that:
          - unit.stdout == '1'
          - rel.results | map(attribute='stat.exists') | min
        quiet: true
text
molecule test (expected, not run: no Docker in the build environment)
1  dependency   ansible-galaxy collection install -r ../../requirements.yml
2  destroy/create   docker container orders-api-noble with systemd as PID 1
3  syntax       ansible-playbook converge.yml --syntax-check
4  converge     role applied once                                   -> changed=N
5  idempotence  role applied again; any "changed" task fails the run -> changed=0 required
6  verify       verify.yml: service running and enabled, /healthz version, env file 0640 root
7  destroy
ran instead (transcripts 10, 45): playbooks/verify.yml against the lab trees -> every host ok, changed=0, failed=0

Real scenarios:

  • A pull request adds shell: systemctl restart nginx to a role; ansible-lint (command-instead-of-module, no-changed-when) fails the check before review.
  • Molecule's idempotence step catches a template with a timestamp: the second converge reports changed.
  • A Molecule scenario on Ubuntu 24.04 and one on Debian 12 catch a package name that differs between them.
LayerToolCatchesSpeed
Parseansible-playbook --syntax-check, YAML parserBad YAML, unknown modules in static tasks, missing rolesSeconds
Rulesansible-lint (profile production)Free-form commands, missing names, non-FQCN modules, risky permissionsSeconds
Inventoryansible-inventory --list + a checker (Go)Missing vars, hosts in two environments, plaintext secretsSeconds
BehaviourMolecule (Docker, Podman, or delegated VMs)Real failures, non-idempotent tasksMinutes
End stateassert, stat, uri in a verify playbookWrong modes, wrong symlink, service not answeringSeconds to minutes
Dry run--check --diff against the real inventoryWhat would change in productionMinutes

Fix / how to use it: all six layers in CI, in that order, before any apply; Molecule per role, not per playbook; verify playbooks that check the end state, not the steps.

Ansible in CI: GitHub Actions, OIDC and short-lived SSH certificates Important ​

In plain words: Run playbooks from a pipeline, not from laptops. The pipeline proves who it is to a secret store with its OIDC token, gets an SSH certificate that expires in ten minutes and the vault password, runs --check --diff, then applies.

Common misunderstanding: "Put the deploy SSH private key in a CI secret." It works, and it is a long-lived root-equivalent key that every workflow with access to the secret can read, that never expires, and that must be rotated on every server when it leaks. A signed SSH certificate with a 10-minute ttl and one principal is useless an hour later.

Definition: the job requests a GitHub OIDC token (permissions: id-token: write), logs in to HashiCorp Vault with the JWT auth method (the hashicorp/vault-action README: "Set up Vault with the JWT auth method", with bound_claims or bound_subject matching the repository and environment), reads the vault password from a KV secret, and asks Vault's SSH secrets engine to sign a fresh public key (ssh-client-signer/sign/<role> with valid_principals and ttl). Hosts trust the SSH CA, not individual keys. The pipeline mechanics (permissions, environments, pinning actions by SHA) are in CI/CD Pipelines.

yaml
# .github/workflows/ansible.yml
# Pull requests: lint, syntax-check, inventory rules (no secrets, no hosts).
# main: deploy with a 10-minute SSH certificate signed by HashiCorp Vault,
# obtained with the job's GitHub OIDC token. No SSH key or vault password
# is stored in GitHub.
name: ansible

on:
  pull_request:
    paths: ["ansible/**", ".github/workflows/ansible.yml"]
  push:
    branches: [main]
    paths: ["ansible/**"]

permissions:
  contents: read

concurrency:
  group: ansible-${{ github.ref }}
  cancel-in-progress: false   # never cancel a half-applied playbook

env:
  ANSIBLE_FORCE_COLOR: "1"
  ANSIBLE_CORE: "ansible-core>=2.21,<2.22"

jobs:
  check:
    runs-on: ubuntu-24.04
    defaults:
      run:
        working-directory: ansible
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
      - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
        with:
          python-version: "3.13"
      - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7
        with:
          go-version-file: go/go.mod
          cache-dependency-path: go/go.mod
      - name: Install Ansible, ansible-lint and collections
        run: |
          python -m pip install "$ANSIBLE_CORE" ansible-lint
          ansible-galaxy collection install -r requirements.yml -p collections
      - name: Syntax check every playbook
        run: |
          for p in playbooks/*.yml; do
            ansible-playbook -i inventories/production "$p" --syntax-check
          done
      - name: ansible-lint (production profile, from .ansible-lint)
        run: ansible-lint
      - name: Inventory rules
        run: |
          go -C ../go build -o "$RUNNER_TEMP/inventorycheck" ./cmd/inventorycheck
          ansible-inventory -i inventories/production --list \
            | "$RUNNER_TEMP/inventorycheck" \
                -require go_service=orders_api_version,orders_api_port \
                -exclusive staging,production

  deploy:
    if: github.event_name == 'push'
    needs: check
    runs-on: ubuntu-24.04
    environment: production          # required reviewers live here
    permissions:
      contents: read
      id-token: write                # lets the job request an OIDC token
    defaults:
      run:
        working-directory: ansible
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
      - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
        with:
          python-version: "3.13"
      - name: Install Ansible and collections
        run: |
          python -m pip install "$ANSIBLE_CORE"
          ansible-galaxy collection install -r requirements.yml -p collections
      - name: Log in to Vault with the GitHub OIDC token; read the vault password
        id: vault
        uses: hashicorp/vault-action@892a26828f195e65540a40b4768ae4571f51ebfc # v4.0.0
        with:
          url: https://vault.internal.example.com:8200
          method: jwt
          role: ansible-deploy        # bound to repo:acme/infra:environment:production
          exportToken: true           # VAULT_TOKEN for the signing call below
          secrets: |
            kv/data/ansible/production vault_password | ANSIBLE_VAULT_PASSWORD
      - name: Short-lived SSH certificate (Vault SSH secrets engine)
        run: |
          ssh-keygen -q -t ed25519 -N "" -f "$RUNNER_TEMP/id_ed25519"
          jq -n --arg k "$(cat "$RUNNER_TEMP/id_ed25519.pub")" \
             '{public_key: $k, valid_principals: "deploy", ttl: "10m"}' \
          | curl -sf -H "X-Vault-Token: $VAULT_TOKEN" -X POST --data @- \
              "$VAULT_ADDR/v1/ssh-client-signer/sign/ansible-deploy" \
          | jq -r .data.signed_key > "$RUNNER_TEMP/id_ed25519-cert.pub"
          ssh-keygen -L -f "$RUNNER_TEMP/id_ed25519-cert.pub" | grep -E 'Valid|Principals' -A1
      - name: Dry run (check + diff), then apply
        env:
          ANSIBLE_PRIVATE_KEY_FILE: ${{ runner.temp }}/id_ed25519
          ANSIBLE_HOST_KEY_CHECKING: "True"
        run: |
          # Host keys come from the repository, never from first contact.
          install -m 600 known_hosts "$RUNNER_TEMP/known_hosts"
          export ANSIBLE_SSH_ARGS="-o UserKnownHostsFile=$RUNNER_TEMP/known_hosts -o ControlMaster=auto -o ControlPersist=60s"
          ansible-playbook -i inventories/production playbooks/site.yml \
            --vault-id prod@../scripts/vault-pass-from-env.sh --check --diff
          ansible-playbook -i inventories/production playbooks/site.yml \
            --vault-id prod@../scripts/vault-pass-from-env.sh
text
# SSH host keys for the production fleet. Hosts present certificates signed by
# the Vault ssh-host-signer CA, so one line trusts them all:
#   @cert-authority *.prod ssh-ed25519 <host CA public key: vault read -field=public_key ssh-host-signer/config/ca>
text
deploy job (expected, not run: no runner, no Vault in the build environment)
1  GitHub issues an OIDC token: sub=repo:acme/infra:environment:production
2  vault-action -> Vault auth/jwt/login role=ansible-deploy -> VAULT_TOKEN (bound to that sub)
3  read kv/data/ansible/production vault_password -> ANSIBLE_VAULT_PASSWORD (masked)
4  ssh-keygen ed25519 -> POST ssh-client-signer/sign/ansible-deploy {valid_principals: deploy, ttl: 10m}
5  ansible-playbook --check --diff      (logged for review)
6  ansible-playbook                     (applies, serial batches)
7  job ends: the certificate expires in minutes, the private key dies with the runner

Real scenarios:

  • A contractor's laptop with the shared deploy key is stolen; with CI-only, certificate-based access there is no key to revoke.
  • The production environment in GitHub requires a reviewer; the reviewer reads the --check --diff output of the same commit before approving.
  • GitLab CI does the same with id_tokens: and Vault's JWT auth; Jenkins with the HashiCorp Vault plugin.

Fix / how to use it: no long-lived keys in CI; OIDC to a secret store; SSH certificates or AWS SSM Session Manager (amazon.aws.aws_ssm connection) for access; --check --diff as a separate, logged step; one concurrency group per environment so two applies never overlap.

AWX, Ansible Automation Platform and execution environments Good to know ​

In plain words: AWX is a web application and API around ansible-playbook: inventories, credentials, job templates, schedules, RBAC and logs in one place. Red Hat Ansible Automation Platform (AAP) is the supported product built on it. Execution environments are container images that contain Ansible, collections and Python dependencies, so every run uses the same toolchain.

Common misunderstanding: "AWX makes Ansible pull-based." AWX still pushes over SSH; it adds scheduling (a periodic job is how you get drift correction), callbacks for new hosts, and an audit trail.

Definition: the AWX README: "It is one of the upstream projects for Red Hat Ansible Automation Platform." "Ansible uses container images known as Execution Environments (EE) that act as control nodes"; they are built with ansible-builder from an execution-environment.yml and run locally with ansible-navigator. AWX runs every job inside an EE. In AAP the AWX-derived part is the automation controller; private automation hub hosts collections and EEs.

NeedPlain CLI + CIAWX / AAP
Who ran what, whenCI logsJob history, per-user RBAC
CredentialsCI secrets / OIDCCredential store, external lookups
Schedules (drift correction)CI cronBuilt-in schedules
Self-service ("restart orders-api")Workflow dispatchJob templates with surveys
Same toolchain everywherePinned pip + requirements.ymlExecution environment images

Fix / how to use it: start with CI; move to AWX/AAP when many teams need self-service jobs, RBAC on credentials and schedules; build EEs either way so local, CI and AWX runs are identical.

Chef: cookbooks, recipes, Chef Infra Server and the pull model Good to know ​

In plain words: Chef describes hosts in Ruby. Recipes (lists of resources) are packaged in cookbooks, uploaded to Chef Infra Server, and every node's Chef Infra Client downloads them and applies them on a schedule.

Common misunderstanding: "Chef is declarative like Puppet." Resources are declarative, but a recipe is Ruby executed top to bottom, so ordering is the file order and arbitrary Ruby can run between resources; that power is also the main source of non-idempotent Chef code.

Definition: "A cookbook is the fundamental unit of configuration and policy distribution in Chef Infra." A recipe "Is authored using Ruby", "Is mostly a collection of resources", "Must be stored in a cookbook". The pull model: "Periodically, Chef Infra Client contacts the Chef Infra Server to retrieve the latest cookbooks", and "Chef Infra is constructed so that most of the computational effort occurs on the nodes rather than on the Chef Infra Server." Tools: knife and chef on the workstation, data bags for shared data, Ohai for node attributes, Test Kitchen and InSpec for tests.

ruby
# Chef Infra: cookbook "orders_api", recipe "default". Ruby DSL; resources
# run in the order written; notifications queue a restart like a handler.
# The node pulls this from Chef Infra Server on every chef-client run.

user 'orders-api' do
  system true
  shell '/usr/sbin/nologin'
end

directory '/etc/orders-api' do
  owner 'root'
  group 'orders-api'
  mode '0750'
end

template '/etc/orders-api/orders-api.env' do
  source 'orders-api.env.erb'
  owner 'root'
  group 'orders-api'
  mode '0640'
  sensitive true # keep the content out of logs and diffs
  variables(db_password: data_bag_item('orders_api', 'db')['password'])
  notifies :restart, 'systemd_unit[orders-api.service]', :delayed
end

systemd_unit 'orders-api.service' do
  content <<~UNIT
    [Unit]
    Description=orders-api
    [Service]
    EnvironmentFile=/etc/orders-api/orders-api.env
    ExecStart=/opt/orders-api/current/orders-api
    User=orders-api
    [Install]
    WantedBy=multi-user.target
  UNIT
  action [:create, :enable, :start]
end

Fix / how to use it: Chef fits shops already invested in Ruby and in a server-based model with continuous convergence; for a new setup the choice is usually between Ansible and an image pipeline.

Puppet: manifests, the declarative resource model, Puppet agent and server, Puppet Bolt Good to know ​

In plain words: Puppet describes resources (users, files, services) in its own declarative language. A Puppet agent on each node sends facts to the primary server, gets back a compiled catalog, and applies it, every 30 minutes by default. Bolt is Puppet's agentless, push-style tool for one-off tasks.

Common misunderstanding: "Resources run in the order written." A catalog is a graph; order comes from relationships (->, ~>, require, before, notify, subscribe). Two resources without a relationship can apply in any order.

Definition: "Puppet is configured in an agent-server architecture, in which a primary server node controls configuration information for a fleet of managed agent nodes." "An agent node sends facts to the primary server and requests a catalog." "You'll describe the desired state of your system in files called manifests." "Puppet then compiles those manifests into catalogs, and applies each catalog to its corresponding node". "Resources are the fundamental unit for modeling system configurations." The runinterval setting: "How often puppet agent applies the catalog ... Default: 30m". Bolt: "Bolt can be installed on your local workstation and connects directly to remote targets with SSH or WinRM, so you are not required to install any agent software." Data per node comes from Hiera.

puppet
# Puppet: class orders_api (manifests/init.pp in a module). Declarative:
# the catalog is a graph; order comes from relationships (-> and ~>), not
# from the position of a resource in the file. The agent applies it every
# 30 minutes by default.
class orders_api (
  String $version,
  Sensitive[String] $db_password,
) {
  user { 'orders-api':
    ensure => present,
    system => true,
    shell  => '/usr/sbin/nologin',
  }

  file { '/etc/orders-api':
    ensure => directory,
    owner  => 'root',
    group  => 'orders-api',
    mode   => '0750',
  }

  file { '/etc/orders-api/orders-api.env':
    ensure  => file,
    owner   => 'root',
    group   => 'orders-api',
    mode    => '0640',
    content => epp('orders_api/orders-api.env.epp', { 'db_password' => $db_password }),
  }

  service { 'orders-api':
    ensure => running,
    enable => true,
  }

  # ~> means "before, and refresh (restart) on change": the handler idea.
  User['orders-api'] -> File['/etc/orders-api'] -> File['/etc/orders-api/orders-api.env'] ~> Service['orders-api']
}

Fix / how to use it: Puppet fits large, long-lived fleets where continuous enforcement and reporting matter more than orchestration (compliance baselines on thousands of servers); Bolt covers the ad-hoc gap.

Salt (SaltStack): master and minions, states, pillar, grains, event bus and reactor Good to know ​

In plain words: Salt keeps a persistent connection from every minion (agent) to a master. The master sends commands or states to thousands of minions in seconds. States are YAML+Jinja files; pillar is per-minion secret data; grains are facts. Everything is an event on a bus, and the reactor can respond to events automatically.

Common misunderstanding: "Salt is just a faster Ansible." The event bus is the difference: a minion starting, a job finishing or a beacon firing is an event, and the reactor can apply states in response, without CI or cron.

Definition: "Built on Python, Salt is an event-driven automation tool and framework to deploy, configure, and manage complex IT systems." "The core of the Salt State system is the SLS, or Structured Layered State." Pillar: "Pillar data is compiled on the master", which "makes pillar useful for storing sensitive data specific to a particular minion." Grains: "Grains are collected for the operating system, domain name, IP address, kernel, OS type, memory, and many other system properties." "The event system uses a publish-subscribe pattern"; the reactor maps event tags (for example salt/minion/*/start) to reactor SLS files. salt-ssh runs states agentless over SSH.

yaml
# Salt state (salt://orders_api/init.sls). YAML + Jinja; the pillar supplies
# secrets per minion; "watch" restarts the service when the file changes.
orders-api-user:
  user.present:
    - name: orders-api
    - system: True
    - shell: /usr/sbin/nologin

/etc/orders-api/orders-api.env:
  file.managed:
    - source: salt://orders_api/files/orders-api.env.jinja
    - template: jinja
    - user: root
    - group: orders-api
    - mode: '0640'
    - makedirs: True
    - show_changes: False
    - context:
        db_password: {{ pillar['orders_api']['db_password'] }}
    - require:
      - user: orders-api-user

orders-api:
  service.running:
    - enable: True
    - watch:
      - file: /etc/orders-api/orders-api.env
yaml
# Salt reactor (master config: reactor: - 'salt/minion/*/start': [/srv/reactor/deploy.sls]).
# When a minion (re)starts and announces itself on the event bus, apply its
# highstate: event-driven convergence, no cron and no CI push.
highstate_new_minion:
  local.state.apply:
    - tgt: {{ data['id'] }}

Fix / how to use it: Salt fits very large fleets that need fast remote execution and event-driven remediation; its operational cost is the master (or a multi-master setup) and minion key management.

When NOT to use configuration management Important ​

In plain words: Do not use Ansible to configure the inside of containers or to deploy to Kubernetes resource by resource. Images and manifests already are a declarative description, and a reconciler already enforces it.

Common misunderstanding: "We use Ansible, so the Kubernetes deploy should be an Ansible playbook too." kubernetes.core.k8s can apply manifests, but it pushes once and forgets; Argo CD or Flux keep reconciling and show drift continuously (GitOps). CM's job in a Kubernetes shop is the nodes (if self-managed), the bastions, the database and legacy VMs, and bootstrapping the cluster tooling.

Thing to configureOwnerWhy not CM
Container contents (packages, PHP extensions, the Go binary)Dockerfile / image buildBuilt once, scanned, signed; Images & Dockerfiles
Kubernetes Deployments, ConfigMaps, SecretsHelm/Kustomize + Argo CD or FluxContinuous reconciliation, drift visible in the UI
Managed services (RDS, Cloud SQL, load balancers)TerraformProvider API with a state file and a plan
Kubernetes nodes on a managed service (EKS, GKE)The provider's node imagesReplaced, not patched
Self-managed nodes (kubelet, containerd, kernel settings), bastions, VPN gateways, database VMs, CI runnersAnsible (or Puppet/Chef/Salt)Long-lived hosts that drift
VMs that run the app directly (this chapter's two roles)AnsibleExactly the use case

Compared: push vs pull, agent vs agentless ​

Push (Ansible, Bolt, salt-ssh) vs pull (Puppet, Chef, Salt minions)Push, agentlessControl nodeinventory, playbooksroles, vault passwordansible-playbook(laptop, CI job, AWX)managed nodesshd + python3managed nodesshd + python3Windows nodeWinRM / SSHSSH1 connect (forks = hosts in flight)2 copy module (or pipeline it over stdin)3 run it, read JSON: ok / changed / failed4 delete it; nothing runs until the next pushDrift is found only when someone runs it(--check --diff on a schedule, or AWX).Pull, agent on every nodePuppet primarycompiles catalogspuppet agentevery 30mfactscatalogChef Infra Servercookbooks, policieschef-clientconverges locallyperiodic fetchSalt masterstates, pillar, reactorsalt-miniongrainsevent bus (both ways)The agent re-applies desired state on a timer:drift is corrected without anyone pushing,at the cost of an agent and a server to run.
AxisAnsiblePuppetChef InfraSalt
Push vs pullPush (ansible-pull rare)Pull (agent, runinterval 30m)Pull (client, periodic)Both (master publish; minion schedule; reactor)
Agent vs agentlessAgentless (SSH, WinRM)Agent + primary serverAgent + Chef Infra ServerMinion + master; salt-ssh agentless
LanguageYAML + Jinja2Puppet DSLRuby DSLYAML + Jinja (SLS)
State modelOrdered tasks, idempotent modulesDeclarative catalog graphOrdered resources in RubyDeclarative states with requisites
Drift correctionOnly when run (schedule it)Every run of the agentEvery client runSchedules, beacons, reactor
SecretsVault, SOPS, lookupsHiera eyaml, Sensitive typeEncrypted data bags, Chef VaultPillar (GPG renderer)
Testingansible-lint, MoleculePDK, rspec-puppet, LitmusCookstyle, Test Kitchen, InSpecsalt-lint, Kitchen-Salt
Scale patternForks, serial, AWX job slicingCompile servers, PuppetDBServer clusters, PolicyfilesSyndic, multi-master
Learning curveLowestMedium (DSL + graph)Highest (Ruby)Medium (many subsystems)
Best atOrchestrated deploys, rolling changes, ad hocContinuous compliance on large fleetsRuby shops, complex logicFast remote execution, event-driven ops

Mechanics ​

What happens when one task runs on one host ​

text
ansible-playbook, task "Environment file from Vault variables" (template module), host web1
1  controller: resolve vars for web1 (22 levels), decrypt vault values in memory
2  controller: action plugin "template" renders orders-api.env.j2 -> text, computes its checksum
3  controller -> host: stat dest (an ansible.builtin.stat module run): exists? checksum? mode?
4  same checksum and mode  -> result {"changed": false}                        -> "ok"
5  different -> copy rendered text to a host temp file, then the copy module moves it into place
   (validate: runs on the temp file first; backup: keeps the old file with a timestamp)
6  result {"changed": true, "diff": ...}  -> "changed"; notify queues "orders-api restart"
7  diff: false on the task -> no diff printed even under --diff
8  next host (up to `forks` hosts in flight), then the next task (linear strategy)

Module code travels as an AnsiballZ payload (a zip of the module and its module_utils, executed by Python on the host); with pipelining = True it is piped over the SSH session's stdin instead of written to the remote temp directory. Every module answers with JSON (changed, failed, msg, rc, stdout, diff...), which is what register stores.

Run order inside a play ​

StepWhat runsHandlers flushed after
1Variables loaded; vars_files, vars_prompt-
2gather_facts (setup module) unless false-
3pre_tasksYes
4roles: (dependencies first, each role once)-
5tasks:Yes (with roles)
6post_tasksYes
7Next serial batch from step 2-
8Next play-

Knobs ​

KnobWhereEffect
-i, --inventoryCLIInventory source (file, directory, plugin config)
-l, --limitCLIHost pattern subset
-t, --tags / --skip-tagsCLITask selection by tag
-C, --check / -D, --diffCLIDry run / show changes
-e, --extra-varsCLILevel 22 variables (@file.yml loads a file)
-f, --forksCLI / forksParallel hosts
-b, --become; -KCLIEscalate; ask for the become password
--vault-id, --ask-vault-passCLIVault secrets
--syntax-check, --list-tasks, --list-tags, --list-hostsCLIStatic inspection
--start-at-task, --stepCLIResume or step through
-v ... -vvvvCLIVerbosity; -vvv shows SSH commands, -vvvv connection debugging
serial, max_fail_percentage, any_errors_fatal, strategy, orderPlayRolling behaviour
throttle, run_once, delegate_to, local_actionTaskPlacement and concurrency
check_mode, diff, no_logTaskPer-task mode overrides
ansible_connection, ansible_host, ansible_user, ansible_port, ansible_python_interpreter, ansible_ssh_common_argsInventory varsHow to reach a host
ansible_group_priorityGroup varMerge order for same-depth groups

Error messages you will actually see ​

Message (verbatim from the lab transcripts)CauseFix
src file does not exist, use "force=yes" if you really want to create the linkfile: state=link to a target that does not exist (here: in --check on a fresh host)Create the target first, or force: in check mode
Unable to change directory before execution: [Errno 2] No such file or directorycommand with chdir into a directory not created yet (check mode)when: not ansible_check_mode, or create it first
couldn't resolve module/action 'community.general.supervisorctl'. This often indicates a misspelling, missing collection, or incorrect module path.Collection not installed on the collections pathansible-galaxy collection install -r requirements.yml
The task includes an option with an undefined variable. The error was: 'orders_api_prot' is undefinedTypo or a variable from a role that is not in scopeFix the name; argument_specs; default() only for real optionals
ERROR! Attempting to decrypt but no vault secrets foundEncrypted vars and no --vault-idPass the vault ID or password file
ERROR! Decryption failed (no vault secrets were found that could decrypt)Wrong password for that vault IDCorrect password; check the label in the header
Failed to connect to the host via ssh: ssh: connect to host 192.0.2.10 port 22: Operation timed out (UNREACHABLE!)Network, security group, bastion missingansible_ssh_common_args: -o ProxyJump=..., check routes
Unable to parse .../inventories/production as an inventory source then No inventory was parsed, only implicit localhost is availableEvery file in the inventory directory was skipped or failed: hosts.ini is ignored by extension, plugin configs whose collection is missing failName the INI file hosts; install the collections; keep plugin configs where credentials exist
NO MORE HOSTS LEFTEvery host of the batch failed or max_fail_percentage was exceededRead the first fatal: above it
non-zero return codecommand/shell exited non-zerofailed_when if that exit code is fine
...ignoringignore_errors: true swallowed a failureVisible as ignored= in the recap

Go ​

The Go service is orders-api, a static binary. The role puts each version in its own release directory, renders an environment file from Vault, installs a socket unit that owns the port and a service unit that runs the binary, flips a current symlink, restarts through a handler, and checks /healthz. A small Go program validates the inventory before any of that runs.

Before ​

bash
# deploy.sh, BEFORE (do not copy): a loop over SSH
for h in orders-1 orders-2 orders-3; do
  scp orders-api "$h":/opt/orders-api/orders-api          # overwrites the running binary in place
  ssh "$h" "echo DB_DSN=postgres://orders:S3cret@db/orders > /etc/orders-api.env"   # secret in the script and shell history
  ssh "$h" "sudo systemctl restart orders-api"            # always restarts, all hosts, no health check
done

Every line is a classic problem: no idempotence (restart every time), no rollback (the old binary is gone), the secret is in the script, all hosts restart at once, and nothing checks that the new process answers. The port is closed between stop and start, so in-flight connections are refused.

After ​

The role (tasks and handlers shown earlier in Check and diff and Handlers); the systemd units, the service tasks that need a real host, and the service itself:

jinja
# {{ ansible_managed }}
[Unit]
Description=orders-api listening socket

[Socket]
ListenStream={{ orders_api_listen }}
NoDelay=true

[Install]
WantedBy=sockets.target
yaml
# Needs root and systemd: expected, not run in the local lab.
- name: Enable the socket (it owns the port, so restarts refuse no connection)
  ansible.builtin.systemd_service:
    name: orders-api.socket
    enabled: true
    state: started
    daemon_reload: true

- name: Enable the service
  ansible.builtin.systemd_service:
    name: orders-api.service
    enabled: true
    state: started

- name: Run notified handlers now (restart before the health check)
  ansible.builtin.meta: flush_handlers

- name: Health check
  ansible.builtin.uri:
    url: "http://{{ orders_api_listen }}/healthz"
    return_content: true
  register: orders_api_health
  until: orders_api_health.status == 200
  retries: "{{ orders_api_health_retries }}"
  delay: 2
  changed_when: false

- name: The running binary is the version we deployed
  ansible.builtin.assert:
    that:
      - orders_api_health.json.version == orders_api_version
    fail_msg: "running {{ orders_api_health.json.version }}, expected {{ orders_api_version }}"
yaml
# Needs root and systemd: expected, not run in the local lab.
- name: Service group
  ansible.builtin.group:
    name: "{{ orders_api_user }}"
    system: true

- name: Service user (no shell, no home)
  ansible.builtin.user:
    name: "{{ orders_api_user }}"
    group: "{{ orders_api_user }}"
    system: true
    shell: /usr/sbin/nologin
    create_home: false
go
// Command orders-api is the static Go binary the go_service Ansible role
// deploys: /healthz for the role's post-deploy check, configuration from the
// environment (the role renders it from Ansible Vault into an env file that
// systemd loads with EnvironmentFile=), and a graceful drain on SIGTERM,
// which is what systemctl stop and restart send by default.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"academy/configuration-management-ansible/activation"
)

// version is set at build time: go build -ldflags "-X main.version=1.4.2".
var version = "dev"

func main() {
	addr := getenv("ORDERS_API_ADDR", "127.0.0.1:8080")
	// The DSN carries a password: read it, never log it.
	if os.Getenv("ORDERS_API_DB_DSN") == "" {
		log.Fatal("ORDERS_API_DB_DSN is not set (the env file from the role is missing)")
	}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"status": "ok", "version": version})
	})

	ln, how, err := activation.Listener(addr)
	if err != nil {
		log.Fatal(err)
	}
	srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()
	go func() {
		log.Printf("orders-api %s serving on %s", version, how)
		if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	<-ctx.Done()
	// Must finish before systemd's TimeoutStopSec (the role sets 30s).
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	log.Print("SIGTERM: draining in-flight requests")
	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Printf("shutdown: %v", err)
	}
	log.Print("stopped")
}

func getenv(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}
go
// Package activation returns the listener the Go service should serve on:
// a socket handed over by systemd (socket activation, LISTEN_FDS) when one
// is present, otherwise a fresh TCP listener on the configured address.
//
// With socket activation the listening socket belongs to the .socket unit,
// not to the process. Restarting the service closes no socket: the kernel
// keeps queueing new connections while the new process starts, which is how
// the Ansible role gets a restart without refused connections.
package activation

import (
	"errors"
	"fmt"
	"net"
	"os"
	"strconv"
)

// firstFD is SD_LISTEN_FDS_START in sd_listen_fds(3): passed sockets start at 3.
const firstFD = 3

// ErrNoSockets means the process was not socket-activated.
var ErrNoSockets = errors.New("activation: no sockets passed by systemd")

// Count reports how many sockets systemd passed to this process.
// It checks LISTEN_PID against pid, as sd_listen_fds(3) requires, so a
// child process that inherited the variables does not take the sockets.
func Count(getenv func(string) string, pid int) (int, error) {
	pidStr := getenv("LISTEN_PID")
	if pidStr == "" {
		return 0, ErrNoSockets
	}
	p, err := strconv.Atoi(pidStr)
	if err != nil {
		return 0, fmt.Errorf("activation: bad LISTEN_PID %q: %w", pidStr, err)
	}
	if p != pid {
		return 0, ErrNoSockets
	}
	n, err := strconv.Atoi(getenv("LISTEN_FDS"))
	if err != nil || n < 1 {
		return 0, fmt.Errorf("activation: bad LISTEN_FDS %q", getenv("LISTEN_FDS"))
	}
	return n, nil
}

// Listener returns the first systemd-passed socket, or listens on addr.
// The second result says which path was taken, for the startup log line.
func Listener(addr string) (net.Listener, string, error) {
	n, err := Count(os.Getenv, os.Getpid())
	if errors.Is(err, ErrNoSockets) {
		l, err := net.Listen("tcp", addr)
		return l, "listen " + addr, err
	}
	if err != nil {
		return nil, "", err
	}
	// Unset so that processes we start do not believe they own the sockets.
	os.Unsetenv("LISTEN_PID")
	os.Unsetenv("LISTEN_FDS")
	os.Unsetenv("LISTEN_FDNAMES")
	f := os.NewFile(uintptr(firstFD), "systemd-socket")
	l, err := net.FileListener(f) // dups the descriptor
	f.Close()
	if err != nil {
		return nil, "", fmt.Errorf("activation: fd %d: %w", firstFD, err)
	}
	return l, fmt.Sprintf("systemd socket (fd %d of %d)", firstFD, n), nil
}
go
package activation

import (
	"errors"
	"testing"
)

func env(m map[string]string) func(string) string {
	return func(k string) string { return m[k] }
}

func TestCount(t *testing.T) {
	cases := []struct {
		name    string
		vars    map[string]string
		pid     int
		want    int
		wantErr error
		anyErr  bool
	}{
		{"not activated", map[string]string{}, 100, 0, ErrNoSockets, false},
		{"for another process", map[string]string{"LISTEN_PID": "99", "LISTEN_FDS": "1"}, 100, 0, ErrNoSockets, false},
		{"one socket", map[string]string{"LISTEN_PID": "100", "LISTEN_FDS": "1"}, 100, 1, nil, false},
		{"two sockets", map[string]string{"LISTEN_PID": "100", "LISTEN_FDS": "2"}, 100, 2, nil, false},
		{"garbage pid", map[string]string{"LISTEN_PID": "x", "LISTEN_FDS": "1"}, 100, 0, nil, true},
		{"zero fds", map[string]string{"LISTEN_PID": "100", "LISTEN_FDS": "0"}, 100, 0, nil, true},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := Count(env(c.vars), c.pid)
			if c.wantErr != nil && !errors.Is(err, c.wantErr) {
				t.Fatalf("err = %v, want %v", err, c.wantErr)
			}
			if c.anyErr && err == nil {
				t.Fatal("want an error")
			}
			if !c.anyErr && c.wantErr == nil && err != nil {
				t.Fatalf("unexpected error %v", err)
			}
			if got != c.want {
				t.Fatalf("got %d, want %d", got, c.want)
			}
		})
	}
}

func TestListenerFallsBackToTCP(t *testing.T) {
	t.Setenv("LISTEN_PID", "")
	l, how, err := Listener("127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer l.Close()
	if how != "listen 127.0.0.1:0" {
		t.Fatalf("how = %q", how)
	}
}

The inventory check that CI runs before the playbook, on ansible-inventory --list output:

go
// Package inventorycheck validates the JSON that `ansible-inventory --list`
// prints, before a playbook runs: required variables per group, secrets that
// are not Vault-encrypted, and hosts that sit in two mutually exclusive
// groups (staging and production at once). It reads the merged view Ansible
// itself computes, so group_vars, host_vars and inventory plugins are all
// already applied.
package inventorycheck

import (
	"encoding/json"
	"fmt"
	"regexp"
	"sort"
	"strings"
)

// Inventory is the subset of `ansible-inventory --list` output we use.
type Inventory struct {
	Groups   map[string]Group
	HostVars map[string]map[string]any
}

// Group is one group entry: direct hosts and child groups.
type Group struct {
	Hosts    []string `json:"hosts"`
	Children []string `json:"children"`
}

// Parse decodes the --list document: every top-level key except _meta is a group.
func Parse(data []byte) (*Inventory, error) {
	var raw map[string]json.RawMessage
	if err := json.Unmarshal(data, &raw); err != nil {
		return nil, fmt.Errorf("inventorycheck: not ansible-inventory --list JSON: %w", err)
	}
	inv := &Inventory{Groups: map[string]Group{}, HostVars: map[string]map[string]any{}}
	for name, msg := range raw {
		if name == "_meta" {
			var meta struct {
				HostVars map[string]map[string]any `json:"hostvars"`
			}
			if err := json.Unmarshal(msg, &meta); err != nil {
				return nil, fmt.Errorf("inventorycheck: _meta: %w", err)
			}
			inv.HostVars = meta.HostVars
			continue
		}
		var g Group
		if err := json.Unmarshal(msg, &g); err != nil {
			return nil, fmt.Errorf("inventorycheck: group %s: %w", name, err)
		}
		inv.Groups[name] = g
	}
	return inv, nil
}

// HostsOf returns every host in group, following children, sorted.
func (inv *Inventory) HostsOf(group string) []string {
	seen := map[string]bool{}
	var walk func(string, map[string]bool)
	walk = func(g string, path map[string]bool) {
		if path[g] {
			return // a cycle; ansible refuses these, be defensive
		}
		path[g] = true
		for _, h := range inv.Groups[g].Hosts {
			seen[h] = true
		}
		for _, c := range inv.Groups[g].Children {
			walk(c, path)
		}
		delete(path, g)
	}
	walk(group, map[string]bool{})
	out := make([]string, 0, len(seen))
	for h := range seen {
		out = append(out, h)
	}
	sort.Strings(out)
	return out
}

// Rules configures the checks.
type Rules struct {
	Required  map[string][]string // group -> variables every host in it must have
	Exclusive [][]string          // sets of groups a host may be in at most one of
	SecretRE  *regexp.Regexp      // variable names that hold secrets
}

// DefaultSecretRE matches the names this repository uses for secrets.
var DefaultSecretRE = regexp.MustCompile(`(?i)(password|passwd|secret|token|api_key|private_key|dsn)`)

// Check returns one human-readable problem per line, sorted; empty means clean.
func Check(inv *Inventory, r Rules) []string {
	var probs []string
	for group, vars := range r.Required {
		for _, h := range inv.HostsOf(group) {
			for _, v := range vars {
				if _, ok := inv.HostVars[h][v]; !ok {
					probs = append(probs, fmt.Sprintf("%s: missing %s (required by group %s)", h, v, group))
				}
			}
		}
	}
	for _, set := range r.Exclusive {
		member := map[string][]string{}
		for _, g := range set {
			for _, h := range inv.HostsOf(g) {
				member[h] = append(member[h], g)
			}
		}
		for h, gs := range member {
			if len(gs) > 1 {
				probs = append(probs, fmt.Sprintf("%s: in mutually exclusive groups %s", h, strings.Join(gs, ", ")))
			}
		}
	}
	re := r.SecretRE
	if re == nil {
		re = DefaultSecretRE
	}
	for h, vars := range inv.HostVars {
		for name, val := range vars {
			// vault_* variables are the Vault-encrypted holders themselves:
			// with a vault password, ansible-inventory prints them decrypted.
			if strings.HasPrefix(name, "vault_") {
				continue
			}
			if re.MatchString(name) && plaintext(val) {
				probs = append(probs, fmt.Sprintf("%s: %s looks like a plaintext secret (vault it or reference a vault_ variable)", h, name))
			}
		}
	}
	sort.Strings(probs)
	return probs
}

// vaultRef matches a Jinja2 reference to a vault_ variable, the
// "indirection" pattern from the Ansible Vault tips.
var vaultRef = regexp.MustCompile(`^\{\{\s*vault_[A-Za-z0-9_]+\s*\}\}$`)

// plaintext reports whether a value is a literal string rather than an
// inline !vault value (printed as {"__ansible_vault": ...}) or a vault_ reference.
func plaintext(v any) bool {
	switch x := v.(type) {
	case map[string]any:
		_, vaulted := x["__ansible_vault"]
		return !vaulted
	case string:
		return x != "" && !vaultRef.MatchString(strings.TrimSpace(x))
	default:
		return false
	}
}
go
package inventorycheck

import (
	"reflect"
	"testing"
)

const doc = `{
  "_meta": {"hostvars": {
    "web1": {"orders_api_port": 8080, "orders_api_version": "1.4.2",
             "orders_api_db_password": "{{ vault_orders_api_db_password }}",
             "vault_orders_api_db_password": "decrypted-by-ansible-inventory"},
    "web2": {"orders_api_port": 8080,
             "orders_api_db_password": "hunter2"},
    "app1": {"laravel_app_key": {"__ansible_vault": "$ANSIBLE_VAULT;1.1;AES256\n6162"}}
  }},
  "all": {"children": ["ungrouped", "go_service", "laravel", "staging", "production"]},
  "go_service": {"hosts": ["web1", "web2"]},
  "laravel": {"children": ["laravel_web"]},
  "laravel_web": {"hosts": ["app1"]},
  "staging": {"hosts": ["web1", "app1"]},
  "production": {"hosts": ["web2", "app1"]}
}`

func TestHostsOfFollowsChildren(t *testing.T) {
	inv, err := Parse([]byte(doc))
	if err != nil {
		t.Fatal(err)
	}
	if got, want := inv.HostsOf("all"), []string{"app1", "web1", "web2"}; !reflect.DeepEqual(got, want) {
		t.Fatalf("HostsOf(all) = %v, want %v", got, want)
	}
	if got := inv.HostsOf("laravel"); !reflect.DeepEqual(got, []string{"app1"}) {
		t.Fatalf("HostsOf(laravel) = %v", got)
	}
}

func TestCheckFindsEveryProblem(t *testing.T) {
	inv, err := Parse([]byte(doc))
	if err != nil {
		t.Fatal(err)
	}
	got := Check(inv, Rules{
		Required:  map[string][]string{"go_service": {"orders_api_port", "orders_api_version"}},
		Exclusive: [][]string{{"staging", "production"}},
	})
	want := []string{
		"app1: in mutually exclusive groups staging, production",
		"web2: missing orders_api_version (required by group go_service)",
		"web2: orders_api_db_password looks like a plaintext secret (vault it or reference a vault_ variable)",
	}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("Check =\n%q\nwant\n%q", got, want)
	}
}

func TestPlaintext(t *testing.T) {
	cases := map[string]struct {
		v    any
		want bool
	}{
		"literal":       {"s3cr3t", true},
		"vault ref":     {"{{ vault_db_password }}", false},
		"other ref":     {"{{ db_password_from_somewhere }}", true},
		"inline vault":  {map[string]any{"__ansible_vault": "$ANSIBLE_VAULT;1.1;AES256"}, false},
		"empty":         {"", false},
		"number":        {float64(5432), false},
		"plain mapping": {map[string]any{"user": "x"}, true},
	}
	for name, c := range cases {
		if got := plaintext(c.v); got != c.want {
			t.Errorf("%s: plaintext(%v) = %v, want %v", name, c.v, got, c.want)
		}
	}
}

func TestParseRejectsGarbage(t *testing.T) {
	if _, err := Parse([]byte("[all]\nweb1\n")); err == nil {
		t.Fatal("INI text must not parse as --list JSON")
	}
}
go
// Command inventorycheck reads `ansible-inventory --list` JSON on stdin and
// exits 1 with one line per problem. CI runs it before ansible-playbook:
//
//	ansible-inventory -i inventories/production --list \
//	  | inventorycheck -require go_service=orders_api_port,orders_api_version \
//	                   -exclusive staging,production
package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"strings"

	"academy/configuration-management-ansible/inventorycheck"
)

type multi []string

func (m *multi) String() string     { return strings.Join(*m, " ") }
func (m *multi) Set(v string) error { *m = append(*m, v); return nil }

func main() {
	var req, excl multi
	flag.Var(&req, "require", "group=var1,var2 (repeatable)")
	flag.Var(&excl, "exclusive", "groupA,groupB: a host may be in only one (repeatable)")
	flag.Parse()

	rules := inventorycheck.Rules{Required: map[string][]string{}}
	for _, r := range req {
		g, vars, ok := strings.Cut(r, "=")
		if !ok {
			fmt.Fprintf(os.Stderr, "bad -require %q\n", r)
			os.Exit(2)
		}
		rules.Required[g] = append(rules.Required[g], strings.Split(vars, ",")...)
	}
	for _, e := range excl {
		rules.Exclusive = append(rules.Exclusive, strings.Split(e, ","))
	}

	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	inv, err := inventorycheck.Parse(data)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	probs := inventorycheck.Check(inv, rules)
	for _, p := range probs {
		fmt.Println(p)
	}
	fmt.Printf("%d hosts, %d problems\n", len(inv.HostVars), len(probs))
	if len(probs) > 0 {
		os.Exit(1)
	}
}
text
module academy/configuration-management-ansible

go 1.24

The lab runner that builds the binary the role deploys and runs every command against the lab:

bash
#!/usr/bin/env bash
# Run an Ansible command against the local lab.
#   scripts/lab.sh <workdir> ansible-playbook playbooks/site.yml [args...]
# Everything Ansible writes (targets, temp files, fact cache, the orders-api
# binary) goes under <workdir>; the snippet tree is only read.
set -euo pipefail
here=$(cd "$(dirname "$0")/.." && pwd)
work=$(mkdir -p "$1" && cd "$1" && pwd); shift

export ANSIBLE_CONFIG="$here/ansible/ansible.cfg"
export ANSIBLE_HOME="$work/.ansible-home"
export ANSIBLE_LOCAL_TEMP="$work/.ansible-home/tmp"
export ANSIBLE_REMOTE_TEMP="$work/.ansible-home/remote-tmp"
export ANSIBLE_CACHE_PLUGIN_CONNECTION="$work/.ansible-facts"
export ANSIBLE_COLLECTIONS_PATH="$work/collections"
export ANSIBLE_NOCOLOR=1
export LAB_ROOT="$work/target"
export LAB_SHARED_DB="$work/target/shared-db.json"

# Build the binary the go_service role deploys (once per version).
version=1.4.2
bin="$work/build/orders-api-$version"
if [ ! -x "$bin" ]; then
  (cd "$here/go" && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 \
     go build -trimpath -ldflags "-X main.version=$version" -o "$bin" ./cmd/orders-api)
fi

cd "$work"
ln -sfn "$here" kb   # so every path Ansible prints is relative: kb/ansible/...
cmd=$1; shift
case "$cmd" in
  ansible-playbook)
    pb=$1; shift
    exec ansible-playbook "kb/ansible/$pb" \
      --vault-id demo@kb/ansible/demo-vault-password.txt \
      -e "orders_api_local_binary=$bin" \
      -e "laravel_local_src=$work/kb/php/shop" "$@" ;;
  *)
    exec "$cmd" "$@" ;;
esac

The Go angle ​

  • Go binary deploy is the easy case for CM. CGO_ENABLED=0 go build -trimpath -ldflags "-X main.version=1.4.2" produces one static file (the lab's file output: "ELF 64-bit LSB executable, x86-64 ... statically linked"); the role copies it into releases/<version>/, which makes rollback a symlink flip (-e orders_api_version=1.4.1). In production, get_url with checksum: sha256:... fetches it from the artifact store; the checksum makes the task idempotent and tamper-evident.
  • Restart vs reload. systemctl reload "Asks all units listed on the command line to reload their configuration"; it only works if the unit has ExecReload= (or Type=notify-reload) and the program handles the signal. A Go server has no built-in reload; a new binary always needs a restart. Making the restart invisible is the socket's job.
  • Zero-downtime restart with socket activation. With orders-api.socket owning ListenStream=127.0.0.1:8080, systemd passes the listening socket as file descriptor 3 (SD_LISTEN_FDS_START, "the remaining descriptors follow at 4, 5, 6") and sets LISTEN_PID/LISTEN_FDS. During a restart the socket stays open and the kernel queues new connections until the new process calls Accept; nothing is refused. activation.Listener implements the check from sd_listen_fds(3) with the standard library only (os.NewFile(3) + net.FileListener), falling back to net.Listen when not activated (the lab run: "serving on listen 127.0.0.1:18089"). github.com/coreos/go-systemd/activation does the same if you prefer a dependency.
  • Graceful drain. systemd sends SIGTERM on stop and restart; signal.NotifyContext + http.Server.Shutdown drains in-flight requests within 20 s, below TimeoutStopSec=30 after which systemd sends SIGKILL. The lab run shows "SIGTERM: draining in-flight requests" then "stopped", exit 0.
  • Config from the environment, secrets never logged. The role writes /etc/orders-api/orders-api.env (0640, root:orders-api, diff: false), the unit loads it with EnvironmentFile=, and the program refuses to start without ORDERS_API_DB_DSN (lab: "ORDERS_API_DB_DSN is not set (the env file from the role is missing)", exit 1) but never prints it.
  • Health check closes the loop. After meta: flush_handlers the role polls /healthz with uri + until/retries and asserts the reported version equals the inventory's, so "the restart worked" means "the new version answers", not "systemctl returned 0".
  • Validate inputs in Go before Ansible runs. inventorycheck reads the merged inventory (ansible-inventory --list already applied group_vars, host_vars and plugins), fails on missing required variables, hosts in both staging and production, and secret-looking variables that are neither !vault values nor {{ vault_* }} references. It skips vault_* names because, with a vault password, ansible-inventory prints them decrypted.

Laravel ​

The Laravel app is shop: PHP-FPM behind Nginx, queue workers, migrations. The role uses the release-directory layout that Deployer and Envoyer popularised: each release in releases/<id>, storage and .env shared, current a symlink that Nginx serves through $realpath_root.

Before ​

bash
# deploy.sh on the server, BEFORE (do not copy)
cd /var/www/shop
git pull                                  # half-updated code is live while this runs
composer install --no-dev                 # vendor/ changes under running requests
php artisan migrate --force               # on every web server: N concurrent migrations
php artisan config:cache
sudo systemctl restart php8.4-fpm         # drops in-flight requests; reload would not
# queue workers keep running the OLD code until someone remembers to restart them

After ​

yaml
- name: PHP-FPM, Nginx, Supervisor and the app user (real hosts only)
  ansible.builtin.include_tasks: system.yml
  when: cm_manage_system | bool
  tags: [system]

- name: Shared directories survive every release (owned by the app user)
  ansible.builtin.file:
    path: "{{ laravel_home }}/{{ item }}"
    state: directory
    mode: "0775"
    owner: "{{ laravel_user if cm_manage_system | bool else omit }}"
    group: "{{ laravel_user if cm_manage_system | bool else omit }}"
  loop:
    - releases
    - shared/storage/app/public
    - shared/storage/framework/cache/data
    - shared/storage/framework/sessions
    - shared/storage/framework/views
    - shared/storage/logs
  tags: [release]

- name: Check out the release as the app user (real hosts)
  become_user: "{{ laravel_user }}"   # inert when become is false (the lab)
  ansible.builtin.git:
    repo: "{{ laravel_repo }}"
    version: "{{ laravel_release }}"
    dest: "{{ laravel_release_dir }}"
    depth: 1
  when: laravel_local_src is not defined
  tags: [release]

- name: Composer install as the app user (real hosts)
  become_user: "{{ laravel_user }}"
  community.general.composer:
    command: install
    working_dir: "{{ laravel_release_dir }}"
    no_dev: true
    optimize_autoloader: true
  when: laravel_local_src is not defined
  tags: [release]

- name: Copy the release from the controller (local lab)
  ansible.builtin.copy:
    src: "{{ laravel_local_src }}/"
    dest: "{{ laravel_release_dir }}/"
    mode: preserve
  when: laravel_local_src is defined
  tags: [release]

- name: .env from Vault variables (shared between releases; root-owned, readable by the app group)
  ansible.builtin.template:
    src: env.j2
    dest: "{{ laravel_home }}/shared/.env"
    mode: "0640"
    owner: "{{ 'root' if cm_manage_system | bool else omit }}"
    group: "{{ laravel_user if cm_manage_system | bool else omit }}"
  diff: false
  notify: laravel config changed
  tags: [config]

- name: Link shared .env and storage into the release
  ansible.builtin.file:
    src: "{{ item.src }}"
    dest: "{{ laravel_release_dir }}/{{ item.dest }}"
    state: link
    force: true
  loop:
    - { src: ../../shared/.env, dest: .env }
    - { src: ../../shared/storage, dest: storage }
  tags: [release]

- name: Build the framework caches once per release
  become_user: "{{ laravel_user }}"
  ansible.builtin.command:
    cmd: php artisan optimize
    chdir: "{{ laravel_release_dir }}"
    creates: "{{ laravel_release_dir }}/bootstrap/cache/config.php"
  # chdir into a release that --check did not create would fail the dry run.
  when: not ansible_check_mode
  tags: [release]

- name: Migrate the database once, from one host
  become_user: "{{ laravel_user }}"
  ansible.builtin.command:
    cmd: php artisan migrate --force --no-interaction
    chdir: "{{ laravel_release_dir }}"
  register: laravel_migrate_out
  changed_when: "'Nothing to migrate' not in laravel_migrate_out.stdout"
  # Not run_once: with serial, run_once means once per batch. The first host of
  # the whole play (ansible_play_hosts_all ignores batches) migrates, once.
  when:
    - laravel_migrate | bool
    - inventory_hostname == ansible_play_hosts_all[0]
    - not ansible_check_mode
  tags: [release, migrate]

- name: Point current at the release
  ansible.builtin.file:
    src: "releases/{{ laravel_release }}"
    dest: "{{ laravel_home }}/current"
    state: link
    force: "{{ ansible_check_mode }}"
  notify:
    - reload php-fpm
    - restart queue workers
  tags: [release]

- name: Config directories (created by the packages on real hosts)
  ansible.builtin.file:
    path: "{{ cm_root }}{{ item }}"
    state: directory
    mode: "0755"
  loop:
    - "/etc/php/{{ php_version }}/fpm/pool.d"
    - /etc/nginx/sites-enabled
    - /etc/supervisor/conf.d
  tags: [config]

- name: PHP-FPM pool
  ansible.builtin.template:
    src: php-fpm-pool.conf.j2
    dest: "{{ cm_root }}/etc/php/{{ php_version }}/fpm/pool.d/shop.conf"
    mode: "0644"
    validate: "{{ ('php-fpm' ~ php_version ~ ' -t -y %s') if cm_manage_system | bool else omit }}"
  notify: reload php-fpm
  tags: [config]

- name: Nginx site
  ansible.builtin.template:
    src: nginx-site.conf.j2
    dest: "{{ cm_root }}/etc/nginx/sites-enabled/shop.conf"
    mode: "0644"
  notify: reload nginx
  tags: [config]

- name: Queue workers as a systemd template unit
  ansible.builtin.template:
    src: shop-queue@.service.j2
    dest: "{{ cm_root }}/etc/systemd/system/shop-queue@.service"
    mode: "0644"
  when: laravel_queue_manager == 'systemd'
  notify: restart queue workers
  tags: [config]

- name: Queue workers under Supervisor
  ansible.builtin.template:
    src: supervisor-queue.conf.j2
    dest: "{{ cm_root }}/etc/supervisor/conf.d/shop-queue.conf"
    mode: "0644"
  when: laravel_queue_manager == 'supervisor'
  notify: restart queue workers
  tags: [config]

- name: Find old releases
  ansible.builtin.find:
    paths: "{{ laravel_home }}/releases"
    file_type: directory
  register: laravel_releases
  tags: [release]

- name: Remove all but the newest releases
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ (laravel_releases.files | sort(attribute='mtime'))[:-laravel_keep_releases] }}"
  loop_control:
    label: "{{ item.path | basename }}"
  when: item.path | basename != laravel_release
  tags: [release]

- name: Enable queue workers (real hosts only)
  ansible.builtin.include_tasks: service.yml
  when: cm_manage_system | bool
  tags: [system]
yaml
- name: Rebuild Laravel caches
  become_user: "{{ laravel_user }}"
  ansible.builtin.command:
    cmd: php artisan optimize
    chdir: "{{ laravel_home }}/current"
  when: not ansible_check_mode
  listen: laravel config changed

- name: Reload PHP-FPM
  ansible.builtin.service:
    name: "php{{ php_version }}-fpm"
    state: reloaded       # graceful: workers finish their request, OPcache is reset
  when: cm_manage_system | bool
  listen:
    - laravel config changed
    - reload php-fpm

- name: Test the Nginx configuration
  ansible.builtin.command:
    cmd: nginx -t
  changed_when: false
  when: cm_manage_system | bool
  listen: reload nginx

- name: Reload Nginx
  ansible.builtin.service:
    name: nginx
    state: reloaded
  when: cm_manage_system | bool
  listen: reload nginx

- name: Reload PHP-FPM and Nginx (local stand-in, no services in the lab)
  ansible.builtin.debug:
    msg: "stand-in: systemctl reload php{{ php_version }}-fpm / nginx -t && systemctl reload nginx"
  when: not (cm_manage_system | bool)
  listen:
    - laravel config changed
    - reload php-fpm
    - reload nginx

- name: Restart queue workers (they exit after the current job; the manager starts them again)
  become_user: "{{ laravel_user }}"
  ansible.builtin.command:
    cmd: php artisan queue:restart
    chdir: "{{ laravel_home }}/current"
  when: not ansible_check_mode
  listen:
    - laravel config changed
    - restart queue workers
yaml
laravel_release: "0"
laravel_server_name: shop.example.com
php_version: "8.4"
laravel_queue_workers: 2
laravel_queue_manager: systemd        # or: supervisor
laravel_queue_connection: redis
laravel_keep_releases: 3
laravel_migrate: true
laravel_repo: git@github.com:acme/shop.git
laravel_db_connection: pgsql
laravel_db_host: db.internal
laravel_db_database: shop
laravel_db_password: ""                # from vault_laravel_db_password
laravel_app_key: ""                    # from vault_laravel_app_key
yaml
# Needs root and an Ubuntu host with the ondrej/php or distro PHP packages:
# expected, not run in the local lab.
- name: Packages
  ansible.builtin.package:
    name:
      - "php{{ php_version }}-fpm"
      - "php{{ php_version }}-cli"
      - "php{{ php_version }}-pgsql"
      - "php{{ php_version }}-redis"
      - "php{{ php_version }}-mbstring"
      - "php{{ php_version }}-xml"
      - nginx
      - supervisor
      - composer
    state: present

- name: App user
  ansible.builtin.user:
    name: "{{ laravel_user }}"
    system: true
    shell: /usr/sbin/nologin
    home: "{{ laravel_install_dir }}"
    create_home: false

- name: Remove the default Nginx site
  ansible.builtin.file:
    path: /etc/nginx/sites-enabled/default
    state: absent
  notify: reload nginx
yaml
# Needs root and systemd: expected, not run in the local lab.
- name: PHP-FPM and Nginx running and enabled
  ansible.builtin.service:
    name: "{{ item }}"
    state: started
    enabled: true
  loop:
    - "php{{ php_version }}-fpm"
    - nginx

- name: Queue worker instances (systemd)
  ansible.builtin.systemd_service:
    name: "shop-queue@{{ item }}.service"
    state: started
    enabled: true
    daemon_reload: true
  loop: "{{ range(1, laravel_queue_workers + 1) | list }}"
  when: laravel_queue_manager == 'systemd'

- name: Queue workers (Supervisor picks up the new program)
  community.general.supervisorctl:
    name: "shop-queue:"
    state: present
  when: laravel_queue_manager == 'supervisor'

- name: Run notified handlers before the smoke test
  ansible.builtin.meta: flush_handlers

- name: Smoke test through Nginx (Laravel's /up health route)
  ansible.builtin.uri:
    url: "http://127.0.0.1/up"
    headers:
      Host: "{{ laravel_server_name }}"
  register: laravel_up
  until: laravel_up.status == 200
  retries: 10
  delay: 2
  changed_when: false
jinja
# {{ ansible_managed }}
APP_NAME=Shop
APP_ENV={{ app_env | default('production') }}
APP_KEY={{ laravel_app_key }}
APP_DEBUG=false
APP_URL=https://{{ laravel_server_name }}

LOG_CHANNEL=stack
LOG_LEVEL=info

DB_CONNECTION={{ laravel_db_connection }}
DB_HOST={{ laravel_db_host }}
DB_PORT=5432
DB_DATABASE={{ laravel_db_database }}
DB_USERNAME=shop
DB_PASSWORD="{{ laravel_db_password }}"

QUEUE_CONNECTION={{ laravel_queue_connection }}
CACHE_STORE=redis
SESSION_DRIVER=redis
REDIS_HOST=redis.internal
jinja
; {{ ansible_managed }}
[shop]
user = {{ laravel_user }}
group = {{ laravel_user }}
listen = {{ laravel_fpm_socket }}
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6
pm.max_requests = 500

; FPM's ping/status for the load balancer and monitoring
ping.path = /fpm-ping
pm.status_path = /fpm-status

php_admin_value[error_log] = /var/log/php{{ php_version }}-fpm-shop.log
php_admin_flag[log_errors] = on
jinja
# {{ ansible_managed }}
server {
    listen 80;
    server_name {{ laravel_server_name }};
    root {{ laravel_install_dir }}/current/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:{{ laravel_fpm_socket }};
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known) {
        deny all;
    }
}
jinja
# {{ ansible_managed }}
# One unit file, N instances: systemctl enable --now shop-queue@1 shop-queue@2
[Unit]
Description=shop queue worker %i
After=network-online.target

[Service]
User={{ laravel_user }}
Group={{ laravel_user }}
WorkingDirectory={{ laravel_install_dir }}/current
ExecStart=/usr/bin/php{{ php_version }} artisan queue:work {{ laravel_queue_connection }} --sleep=3 --tries=3 --max-time=3600
# queue:restart and --max-time make the worker exit 0; systemd starts it again.
Restart=always
RestartSec=1
# Longer than the longest job, so a stop lets the current job finish.
TimeoutStopSec=300
KillSignal=SIGTERM

[Install]
WantedBy=multi-user.target
jinja
; {{ ansible_managed }}
[program:shop-queue]
process_name=%(program_name)s_%(process_num)02d
command=/usr/bin/php{{ php_version }} {{ laravel_install_dir }}/current/artisan queue:work {{ laravel_queue_connection }} --sleep=3 --tries=3 --max-time=3600
user={{ laravel_user }}
numprocs={{ laravel_queue_workers }}
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
stopwaitsecs=300
redirect_stderr=true
stdout_logfile={{ laravel_install_dir }}/shared/storage/logs/worker.log

The lab replaces Laravel's artisan with a stand-in that implements only the three commands the role calls, so the command tasks and their changed_when logic run for real without a framework install:

php
<?php

// LAB STAND-IN for Laravel's artisan, so the laravel_app role's command tasks
// run for real without a framework install. It implements only the three
// commands the role calls and prints the line the role's changed_when reads.
// A real release ships Laravel's own artisan file here.

declare(strict_types=1);

$base = __DIR__;
$cmd = $argv[1] ?? 'list';

/** Write a file or fail loudly: a stand-in that ignores a failed write lies to changed_when. */
function write_or_die(string $path, string $data): void
{
    if (@file_put_contents($path, $data) === false) {
        fwrite(STDERR, "lab stand-in: cannot write {$path}\n");
        exit(1);
    }
}

/** Read KEY=value lines from the release's .env (a symlink to shared/.env). */
function env_file(string $path): array
{
    $vars = [];
    foreach (@file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
        if ($line[0] === '#' || !str_contains($line, '=')) {
            continue;
        }
        [$k, $v] = explode('=', $line, 2);
        $vars[$k] = trim($v, '"');
    }
    return $vars;
}

switch ($cmd) {
    case 'optimize':
        // Laravel writes bootstrap/cache/config.php, routes-v7.php, events.php...
        $env = env_file($base . '/.env');
        if (!isset($env['APP_KEY']) || $env['APP_KEY'] === '') {
            fwrite(STDERR, "No application encryption key has been specified.\n");
            exit(1);
        }
        write_or_die($base . '/bootstrap/cache/config.php', "<?php return ['app' => ['env' => " . var_export($env['APP_ENV'] ?? 'production', true) . "]];\n");
        echo "  INFO  Caching framework bootstrap, configuration, and metadata.\n";
        exit(0);

    case 'migrate':
        if (!in_array('--force', $argv, true)) {
            fwrite(STDERR, "Refusing to run in production without --force.\n");
            exit(1);
        }
        $env = env_file($base . '/.env');
        $db = $env['DB_DATABASE'] ?? '';
        if ($db === '' || $db[0] !== '/') {
            fwrite(STDERR, "Lab stand-in needs an absolute DB_DATABASE path.\n");
            exit(1);
        }
        $done = is_file($db) ? json_decode((string) file_get_contents($db), true) : [];
        $all = array_map(fn ($f) => basename($f, '.php'), glob($base . '/database/migrations/*.php') ?: []);
        sort($all);
        $pending = array_values(array_diff($all, $done));
        if ($pending === []) {
            echo "  INFO  Nothing to migrate.\n";
            exit(0);
        }
        echo "  INFO  Running migrations.\n";
        foreach ($pending as $m) {
            echo "  {$m} DONE\n";
            $done[] = $m;
        }
        write_or_die($db, json_encode($done, JSON_PRETTY_PRINT) . "\n");
        exit(0);

    case 'queue:restart':
        // Laravel stores illuminate:queue:restart in the cache; workers poll it.
        write_or_die($base . '/storage/framework/cache/data/queue-restart', (string) time());
        echo "  INFO  Broadcasting queue restart signal.\n";
        exit(0);

    default:
        fwrite(STDERR, "lab stand-in: command {$cmd} not implemented\n");
        exit(1);
}
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Expand step: nullable column, no lock-heavy default rewrite.
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->unsignedBigInteger('total_cents')->nullable();
        });
    }

    public function down(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn('total_cents');
        });
    }
};
text
ran: a new release on both Laravel hosts (transcript 14, -e laravel_release=2026.11.30-1 --limit laravel -v)
app1 (first host of the play)
1  copy release from controller                 changed
2  php artisan optimize (creates: .../bootstrap/cache/config.php)   changed  (new release has no cache yet)
3  php artisan migrate --force                  ok       stdout "INFO  Nothing to migrate."  -> changed_when false
4  Point current at the release                 changed  notify: reload php-fpm, restart queue workers
5  Find old releases / remove beyond 3          ok
6  handlers: Reload PHP-FPM and Nginx (stand-in) ok; php artisan queue:restart  changed
app2
3  migrate                                      skipping (inventory_hostname != ansible_play_hosts_all[0])
   recap: app1 changed=5, app2 changed=5; releases/ now holds 2026.11.29-1 and 2026.11.30-1

The Laravel angle ​

  • Atomic switch. Nginx's root .../current/public with fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name resolves the symlink per request, so after the flip new requests use the new release while old ones finish in the old directory. systemctl reload php8.4-fpm (the handler, state: reloaded) restarts FPM workers gracefully and clears OPcache, which still caches paths of the previous release.
  • Build once per release. Laravel: "Laravel provides a single, convenient optimize Artisan command that will cache all of these files. This command should typically be invoked as part of your application's deployment process." The role runs it in the release directory with an absolute creates: <release>/bootstrap/cache/config.php, so it runs exactly once per release, and again (handler laravel config changed) only when .env changes. The lab found the trap: creates is resolved inside chdir, so a path written relative to anywhere else never matches and the task runs every time (transcript 38).
  • Migrate once. php artisan migrate --force runs on the first host of the whole play (ansible_play_hosts_all[0]), not with run_once, because the play is batched with serial: "50%" and run_once means once per batch (transcript 37). changed_when: "'Nothing to migrate' not in ..." gives an honest status, so notify fires only when something changed; it is only honest if the command fails when it cannot do its work (the lab's artisan stand-in originally ignored a failed write and claimed to migrate on every run; it now exits 1). Schema changes must be backwards compatible with the release still serving traffic: expand first, contract later (Zero-Downtime Schema Migrations).
  • Queue workers. The docs: "queue workers are long-lived processes and store the booted application state in memory", so they keep running old code until restarted. php artisan queue:restart "will instruct all queue workers to gracefully exit after they finish processing their current job so that no existing jobs are lost"; the process manager starts them again with the new release. The role supports both managers: a systemd template unit shop-queue@.service (Restart=always, instances @1..@N) or Supervisor with numprocs (Laravel's documented setup). Laravel also says stopwaitsecs must exceed your longest job; the same applies to TimeoutStopSec in the systemd unit.
  • .env from Vault, shared across releases; the right owner. Rendered once into shared/.env (root:shop, 0640, diff: false) so the shop FPM pool and workers can read it but not change it, and linked into each release; shared/storage is owned by shop. Git, Composer and every php artisan task run with become_user: shop, so caches and compiled views are never root-owned (inert in the lab, where become is false). APP_KEY comes from a vault_ variable; rotating it is a vault edit plus a run.
  • Health route. "By default, the health check route is served at /up and will return a 200 HTTP response if the application has booted without exceptions"; the role's smoke test calls it through Nginx with the right Host header.
ToolWhat it isModelServer setupZero-downtime releasesWhen to pick it
Ansible role (this chapter)General CMPush over SSHYes (packages, users, FPM, Nginx, workers)Release dirs + symlink (written by you)You also manage the servers, or many apps and stacks
Deployer"Deployer creates a deploy.php or deploy.yaml recipe" with Laravel tasks (artisan:migrate, shared_dirs)Push over SSH, PHPdep provision (basic)Built in (releases, current, locks)PHP team, servers already set up
Laravel Envoy"a tool for executing common tasks you run on your remote servers", Blade syntaxPush over SSHNoOnly what your tasks scriptSmall task runner next to the app
Laravel Forge"a server management and application deployment service"SaaS, provisions and deploysYes, managedDeploy scripts (Envoyer integration)You want servers managed for you
Envoyer"Zero downtime PHP deployment" SaaSSaaS pushNoYesDeploys only, servers exist
Laravel Cloud"a fully-managed Laravel platform"PaaSNot your concernPlatform-managedNo servers at all

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Second run reports changesIdempotent tasksModules over commands; creates, changed_when; stable templatesRestarts only on real change; drift visibleDiscipline; tests (Molecule idempotence)
A hand edit lives on for monthsDrift detectionNightly --check --diff from CI or AWX; or an agent-based toolChanges outside Git show upSomeone must read the report
Bad config takes the fleet downRolling update with a canaryserial: [1, "25%"], max_fail_percentage: 0, drain/enable in pre/post tasksBlast radius of one hostSlower deploys
Restart drops connectionsSocket activation or a drain.socket unit owns the port (Go); reload for PHP-FPM and Nginx; LB drainNo refused requestsProgram must accept an inherited socket
Secrets in Git or logsVault/SOPS + no_logvault_ indirection, diff: false, no_log: true, password from a client scriptSafe at rest and in logsKey distribution and rotation
Variable silently ignoredPrecedence hygieneKnobs in defaults/, constants in vars/, argument_specs, ansible-inventory --hostPredictable valuesA rule everyone must know
Same role, many environmentsInventories per environmentinventories/<env>/group_vars, one vault ID per environmentNo per-environment codeDirectory sprawl
Migrations run on every web serverOne host, oncewhen: inventory_hostname == ansible_play_hosts_all[0] (not run_once with serial)One migration per deployMust be backwards compatible
--check fails on a fresh hostCheck-mode-aware rolesforce: "{{ ansible_check_mode }}"-style arguments, when: not ansible_check_mode on dependent commandsDry runs work everywhereDry run predicts less
Personal SSH keys on serversCI-only access with short-lived certificatesOIDC to HashiCorp Vault, SSH CA, 10-minute ttlNothing to revoke when a laptop is lostVault and SSH CA to run
Slow runs on big fleetsFewer round tripsforks, pipelining, ControlPersist, fact cache, strategy: free where order does not matterMinutes instead of an hourHigher controller load
"Works on my laptop" AnsiblePinned toolchainansible-core range in CI, requirements.yml, execution environmentsSame result everywhereUpgrades are explicit work

Making a playbook idempotent ​

Run it twice; every changed on the second run is a bug. For each, replace a command/shell with a module, or add creates/removes, or a changed_when that reads the command's output, or changed_when: false for read-only commands. Then add the second run to CI (Molecule's idempotence step does exactly this). The lab's two Laravel bugs (a creates path that never matched, run_once under serial) were found this way and then reproduced in isolation (transcripts 37, 38).

Rolling a change safely through 50 hosts ​

serial: [1, 5, "25%"], max_fail_percentage: 0, pre_tasks that drain the host from the load balancer (with delegate_to the LB API host), the role, meta: flush_handlers, a health check with uri + until, post_tasks that re-enable it. A failing canary stops the play before batch 2.

Getting secrets out of Git history and logs ​

Move them to group_vars/<env>/vault.yml under vault_ names, encrypt with a per-environment vault ID, reference them from plain vars, add diff: false or no_log: true to every task that renders them, rotate every secret that was ever in plain text (Git history keeps it), and let CI fetch the vault password from a secret store with OIDC.

Seeing drift without auto-fixing it ​

A scheduled CI job (or an AWX schedule) runs ansible-playbook site.yml --check --diff against production with a read-only identity and posts the diff. The lab reproduced it: a hand-added # drift line in a unit file appeared as -# drift in the check output (transcript 12), and the next real run removed it and restarted the service through the handler (transcript 13).

Choosing ​

Which tool family owns which layer ​

SituationRecommendationExtra techniqueReason
Cloud resources (VPC, VM, DNS, IAM)Terraform / OpenTofuTag VMs for the dynamic inventoryProvider APIs, plan, state
Autoscaled stateless VMsPacker image (Ansible as the provisioner)Replace, never patchImmutable, no drift
Long-lived VMs running apps (this chapter's roles)Ansibleserial, Vault, MoleculeOrchestrated, rolling deploys
Thousands of servers with compliance baselinesPuppet (or Chef)Reports, PuppetDB, HieraContinuous enforcement
Fleet-wide remote execution in seconds, event-driven remediationSaltReactor, beaconsPersistent bus
Applications in KubernetesHelm/Kustomize + Argo CD or FluxESO for secretsContinuous reconciliation
Windows serversAnsible over WinRM/SSH, or DSCansible.windows collectionNo agent needed

Which Ansible tool for the job ​

NeedToolNote
One-off command on many hostsansible <pattern> -m <module> -a ...Ad hoc; use a module, not shell
Repeatable changePlaybook + rolesIn Git, reviewed
Reuse across repositoriesCollection with rolesVersioned on Galaxy or a private hub
Run from a pipelineCI job with pinned ansible-coreOIDC for credentials
Self-service, RBAC, schedulesAWX / Ansible Automation PlatformExecution environments
Test a roleMolecule + ansible-lintIdempotence step

Which secret store ​

Team / platformChoiceWhy
Small team, no cloud KMSAnsible Vault files, one ID per environmentZero dependencies
AWS/GCP/Azure shopSOPS with KMS (community.sops) or the cloud secret manager via lookupIAM decides who decrypts
HashiCorp Vault already in placecommunity.hashi_vault lookup + Vault-issued SSH certificatesRotation, audit, short-lived credentials
Kubernetes workloadsExternal Secrets Operator / sealed secretsDifferent problem; not CM

Which Laravel deploy tool ​

SituationChoice
You manage the servers and other stacks tooAnsible role (this chapter)
PHP team, servers already configured, want a ready recipeDeployer
A few commands over SSH from the repoLaravel Envoy
You want servers provisioned and managed by a serviceLaravel Forge (+ Envoyer for zero-downtime deploys)
No serversLaravel Cloud

In architecture: from a single process to a distributed system ​

CM's role changes as the system grows: from "the thing that sets up the one server" to "the thing that keeps the hosts under a platform boring".

Monolith: one VM, one database ​

One Laravel monolith on one VM with PostgreSQL on a second. The laravel_app role and a postgresql role, one inventory with two hosts, one vault file. The simplest correct setup is exactly this chapter's role without serial (one host) but with the release layout, so a bad deploy is undone with -e laravel_release=<previous>. Even here, run it twice in CI; the second run proves the playbook will not hurt the next deploy.

Modular monolith and shared hosts ​

The monolith is split into modules and a second app (the Go orders-api) appears on the same VMs. Ownership moves into roles: each team owns one role with its own defaults, handlers and tests; a common role (meta dependency) owns users, time, SSH and monitoring agents. Ports, users and paths must not collide, which is a rule the inventory check can enforce. One site.yml imports a play per service so each can be rolled independently with --limit or tags.

Microservices on VMs ​

Twenty services, each with its own release cadence. What survives across service boundaries: one shared common collection, one execution environment, one inventory per environment with groups per service, and the same role contract (versioned binary, env file from Vault, socket + service unit, /healthz, rolling serial). What does not: a single big playbook run for every deploy. Each service's pipeline runs --limit <service-group> with its own role version; the flow for one change is:

text
1  orders-api PR merged -> CI builds orders-api 1.5.0, uploads binary + sha256 to the artifact store
2  CI: ansible-inventory --list | inventorycheck  (required vars, no host in staging and production)
3  CI: ansible-playbook site.yml --limit go_service -e @releases/orders-api.yml --check --diff
4  reviewer approves the production environment
5  CI: same command without --check; serial [1, 50%]; each host: drain -> get_url (checksum) -> units -> symlink
6  handler: restart via the socket-activated unit -> uri /healthz returns version 1.5.0 -> enable
7  payments-api, catalog-api: untouched (different groups), their roles unchanged

Service-to-service settings (URLs, timeouts) live in group_vars, not in each role, so one change rolls through every consumer in one run. Secrets are per service vault files, so a leak is scoped.

Distributed data: replicas, caches, many regions ​

Databases, Redis and message brokers on VMs are where CM stays essential longest, and where order matters most: a PostgreSQL primary and replicas need the primary configured first, replicas pointed at it, and a restart of the primary only with a failover plan. Patterns: one play per tier with serial: 1 and order: sorted; delegate_to the primary for replication slots; throttle: 1 for tasks that touch a shared resource (a schema migration, a cache flush); any_errors_fatal: true for cluster-membership changes where half-applied is worse than not applied. Across regions, a control node (or AWX execution node) per region keeps SSH latency low, and inventories group by region so a change can roll region by region. Caches in front of the app are flushed by handlers, not by tasks, so they flush once and only on change.

Scaling path: 1x, 10x, 100x ​

ScaleHostsWhat changes
1x2-10One repository, static inventory, Vault file, runs from CI; serial once you have two web servers
10x50-500Dynamic inventory from cloud tags, fact caching, forks 50+, pipelining, Molecule per role, collections for shared roles, AWX or a scheduled CI job for drift reports
100x5,000+Execution environments everywhere, AWX/AAP with job slicing and execution nodes per region, or a move to images (Packer) and replacement instead of configuration; agents (Puppet/Salt) where continuous enforcement is required; most application config moves to Kubernetes and GitOps

Lab ​

Everything below ran on the build machine (macOS, Python 3.9.6, ansible-core 2.15.13, community.general 10.7.9 and ansible.posix 1.6.2 installed into the lab's own collections path, Go 1.27.4, PHP 8.6) against the four local aliases. scripts/lab.sh <workdir> ... sets ANSIBLE_CONFIG to the snippet ansible.cfg, points every Ansible temp, fact-cache and collections path into the work directory, builds the Go binary, and passes the throwaway vault ID. Transcripts are saved verbatim under pipeline/sources/configuration-management-ansible/runs/ (absolute paths of the build machine appear in some diff headers and errors). Steps that need real hosts are marked expected, not run.

1. Syntax, parse and inventory (ran) ​

bash
$ for p in site basics errors precedence verify; do scripts/lab.sh "$W" ansible-playbook playbooks/$p.yml --syntax-check; done
# playbook: kb/ansible/playbooks/site.yml   ... exit=0 for all seven playbooks incl. molecule converge/verify (transcript 25)
$ python3 yamlcheck.py docs/snippets/platform/configuration-management-ansible
# vault-encrypted (not YAML until decrypted): ansible/inventories/local/group_vars/all/vault.yml
# 44 YAML files parsed, 0 failed, 1 vault files skipped                                   (transcript 26)
$ scripts/lab.sh "$W" ansible-inventory --graph
# @all: |--@ungrouped: |--@go_service: web1 web2 |--@laravel: app1 app2 |--@staging: web1 app1 |--@production: web2 app2

2. Dry run on an empty tree, then two real runs (ran) ​

bash
$ scripts/lab.sh "$W" ansible-playbook playbooks/site.yml --check --diff       # transcripts 07 and 42
# app1 : ok=13 changed=10 ... failed=0 skipped=14     web1 : ok=13 changed=7 ... failed=0 skipped=7
# ls "$W/target"  -> No such file or directory        (check mode changed nothing)
$ scripts/lab.sh "$W" ansible-playbook playbooks/site.yml                      # transcript 43 (final tree)
# app1 : ok=16 changed=14   app2 : ok=15 changed=13   web1 : ok=12 changed=7   web2 : ok=12 changed=7
$ scripts/lab.sh "$W" ansible-playbook playbooks/site.yml                      # transcript 44 (same as 09 and 30)
# app1 : ok=13 changed=0 unreachable=0 failed=0 skipped=7 rescued=0 ignored=0
# app2 : ok=12 changed=0 unreachable=0 failed=0 skipped=8 rescued=0 ignored=0
# web1 : ok=11 changed=0 unreachable=0 failed=0 skipped=5 rescued=0 ignored=0
# web2 : ok=11 changed=0 unreachable=0 failed=0 skipped=5 rescued=0 ignored=0
$ scripts/lab.sh "$W" ansible-playbook playbooks/verify.yml                    # transcripts 10, 31 and 45
# every host ok, changed=0, failed=0 (stat + assert on modes, symlink target, rendered units)

Before the fixes, the same pair of runs is in transcripts 01-06: three check-mode failures on an empty tree and a non-idempotent second run (changed=2 per Laravel host), each fixed in the role and explained in Check and diff and Idempotence; the two idempotence causes were then reproduced in isolation (transcripts 37 and 38). One more real bug surfaced on the way: with a relative cm_root, ansible-playbook wrote the targets under the playbook directory, not the shell's working directory (and the artisan stand-in, unable to save its state there, silently claimed to migrate every time); the inventory now builds an absolute root from LAB_ROOT and the stand-in exits 1 when it cannot write.

3. Diff, tags, limit, drift (ran) ​

bash
$ scripts/lab.sh "$W" ansible-playbook playbooks/site.yml --tags config --limit web1 --diff -e orders_api_port=8081   # transcript 11
# -ListenStream=127.0.0.1:8080
# +ListenStream=127.0.0.1:8081
# RUNNING HANDLER [go_service : Restart orders-api (local stand-in, no systemd in the lab)]
# web1 : ok=7 changed=2 ... skipped=2
$ echo "# drift" >> "$W/target/web2/etc/systemd/system/orders-api.service"
$ scripts/lab.sh "$W" ansible-playbook playbooks/site.yml --check --diff --limit go_service                         # transcript 12
# -ListenStream=127.0.0.1:8081        (web1: the inventory still says 8080)
# +ListenStream=127.0.0.1:8080
# -# drift                            (web2: the hand edit)
$ scripts/lab.sh "$W" ansible-playbook playbooks/site.yml --limit go_service                                          # transcript 13
# web1 : ok=12 changed=2   web2 : ok=12 changed=1   (both converged back to Git)

4. Precedence, building blocks, error handling (ran) ​

bash
$ scripts/lab.sh "$W" ansible-playbook playbooks/precedence.yml                                   # transcript 15
#     "msg": "web1: from host_vars/web1"
#     "msg": "web2: from group_vars/production"
#     "msg": "app1: from group_vars/all"
#     "msg": "app2: from group_vars/production"
$ scripts/lab.sh "$W" ansible-playbook playbooks/precedence.yml -e demo_color=from-extra-vars     # transcript 16: all four "from-extra-vars"
$ scripts/lab.sh "$W" ansible-playbook playbooks/basics.yml       # run 1: changed=1; run 2: ok=5 changed=0 skipped=1 (transcripts 48, 49)
$ scripts/lab.sh "$W" ansible-playbook playbooks/errors.yml       # run 1: changed=2; run 2: ok=6 changed=0 rescued=1 ignored=1 (46, 47)

5. Vault, the inventory check, the Go service (ran) ​

bash
$ scripts/lab.sh "$W" ansible-vault encrypt_string --vault-id demo@kb/ansible/demo-vault-password.txt --name vault_redis_password lab-only-redis-pw
# vault_redis_password: !vault |
#           $ANSIBLE_VAULT;1.2;AES256;demo ...                                         (transcript 23)
$ scripts/lab.sh "$W" ansible-inventory --list --vault-id demo@... | inventorycheck -require go_service=orders_api_version,orders_api_port -exclusive staging,production
# 4 hosts, 0 problems                                                                   exit=0
$ scripts/lab.sh "$W" ansible-inventory -i bad-inventory.yml --list | inventorycheck -require ... -exclusive staging,production
# orders-1: in mutually exclusive groups staging, production
# orders-1: orders_api_db_password looks like a plaintext secret (vault it or reference a vault_ variable)
# orders-2: missing orders_api_version (required by group go_service)
# 2 hosts, 3 problems                                                                   exit=1   (transcript 22)
$ cd go && gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok  academy/configuration-management-ansible/activation
# ok  academy/configuration-management-ansible/inventorycheck
$ ORDERS_API_ADDR=127.0.0.1:18089 ORDERS_API_DB_DSN=postgres://lab@localhost/orders ./orders-api-darwin &
# orders-api 1.4.2 serving on listen 127.0.0.1:18089
$ curl -s http://127.0.0.1:18089/healthz
# {"status":"ok","version":"1.4.2"}
$ kill -TERM $pid
# SIGTERM: draining in-flight requests
# stopped                                                                               (transcript 24)

6. On real hosts (expected, not run) ​

bash
# Ubuntu 24.04 VMs reachable as deploy@ with sudo; collections installed from requirements.yml
$ ansible-playbook -i inventories/production playbooks/site.yml --vault-id prod@scripts/vault-pass-from-env.sh --check --diff
# expected: packages, users, units would change on a fresh host; no failures (the check-mode guards above)
$ ansible-playbook -i inventories/production playbooks/site.yml --vault-id prod@scripts/vault-pass-from-env.sh
# expected: orders-1 alone first (serial 1), then orders-2 + orders-3; each: socket enabled, service restarted,
#           GET /healthz -> {"status":"ok","version":"1.4.2"}, assert passes; then shop-web-[1:3] in halves
$ ansible-playbook ... (same command again)
# expected: changed=0 on every host
$ curl -sI -H 'Host: shop.example.com' http://shop-web-1.prod/up
# expected: HTTP/1.1 200 OK

7. Molecule and ansible-lint (expected, not run) ​

bash
$ python -m pip install "ansible-core>=2.21,<2.22" ansible-lint molecule "molecule-plugins[docker]"
$ ansible-lint                                  # expected: Passed (production profile) or a list of rule IDs
$ cd ansible/roles/go_service && ORDERS_API_BINARY=/path/to/orders-api molecule test
# expected sequence: dependency, destroy, syntax, create, prepare, converge, idempotence, verify, destroy
# expected: "Idempotence completed successfully." and the verify asserts pass

Common misconceptions ​

BeliefReality
"Ansible is idempotent, so my playbook is."Only if every task is; command/shell report changed every time unless you add creates/changed_when. The lab's first Laravel draft showed changed=2 on its second run until fixed.
"Agentless means nothing on the host."It needs SSH (or WinRM) and Python; no daemon is the difference.
"Vault makes secrets safe.""ONLY protects 'data at rest'"; --diff, -v and ansible-inventory --list print decrypted values.
"vars/main.yml holds a role's defaults."defaults/ is level 2; vars/ is level 15 and beats inventory.
"Handlers run in notify order, and run even if the play fails."Definition order; a failed host skips its handlers unless force_handlers.
"--check passing means the run will pass.""Check mode is just a simulation"; dependent tasks can fail or be skipped (three such failures in the lab).
"serial: 1 runs each task on one host at a time."It runs the whole play per batch; tasks inside a batch are still parallel.
"run_once runs once per playbook run."Once per batch when serial is set (transcript 37: h1, then h2).
"ignore_errors ignores everything."Not undefined variables, connection failures or syntax errors.
"Relative paths are relative to where I ran the command."In the lab's playbook runs, relative module paths landed under the playbook directory, and creates is resolved inside chdir; use absolute paths.
"A host is in one group."Any number; same-depth groups merge alphabetically.
"Terraform replaces Ansible."Different APIs and jobs: resources vs host contents; many teams use both.
"Use Ansible to deploy to Kubernetes."Possible, but GitOps reconciles continuously; CM belongs to the hosts.
"Puppet resources run in file order."The catalog is a graph; use relationships.
"systemctl reload reloads a Go service."Only with ExecReload= and a signal handler; a new binary needs a restart (socket activation hides it).

Cheat sheet ​

TopicRemember
LayersTerraform creates, Packer/Dockerfile bakes, Ansible configures, Argo CD/Flux reconciles
ArchitectureControl node pushes modules over SSH/WinRM; managed nodes need Python; no agent
InventoryStatic INI/YAML or plugins (amazon.aws.aws_ec2); all, ungrouped; group_vars, host_vars
ConfigOne ansible.cfg wins; forks 5 default; pipelining off by default; keep host key checking on
ModulesFQCN always; real module over command over shell
IdempotenceSecond run changed=0; creates, changed_when; Molecule idempotence
HandlersOnce, definition order, end of section; listen; flush_handlers before health checks
Precedence22 levels; defaults lowest, -e highest; role vars/ beats inventory
TemplatesTemplate whole files; validate:; no timestamps; lineinfile only for foreign files
Check/diff--check --diff before apply; guard tasks that cannot predict; diff: false for secrets
Rollingserial: [1, "25%"], max_fail_percentage: 0, drain/enable with always tag
Errorsblock/rescue/always; failed_when over ignore_errors
Rolesdefaults vs vars; meta dependencies run once; argument_specs
Secretsvault_ indirection, vault IDs per env, password client script, or SOPS/lookups
Testing--syntax-check, ansible-lint (production profile), Molecule, verify with assert
CIOIDC to a secret store, short-lived SSH certificates, check then apply, one concurrency group
Go roleRelease dirs, checksummed binary, env file 0640, socket unit + SIGTERM drain, /healthz assert
Laravel roleShared .env/storage, optimize per release, migrate once, current symlink, FPM reload, queue:restart

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is the difference between provisioning, configuration management, image baking and GitOps, and which tool owns each? Must-know ​

Answer

Answer: Provisioning creates resources through provider APIs and keeps state (Terraform, Pulumi, CloudFormation). Configuration management converges the inside of an existing host, repeatedly (Ansible, Puppet, Chef, Salt). Image baking applies that configuration once at build time and boots copies (Packer, Dockerfiles), which is the immutable-infrastructure approach. GitOps reconciles Kubernetes objects from Git continuously (Argo CD, Flux). See CM vs provisioning.

2 — What does "agentless" mean for Ansible, and what does a managed node still need? Must-know ​

Answer

Answer: No Ansible daemon runs on the host: the control node connects over SSH (or WinRM), copies or pipes a module, runs it and removes it. The host still needs an SSH server and Python (PowerShell for Windows), plus a user with the right sudo rule. The raw module is how you bootstrap Python. See Ansible architecture.

3 — Why does a command task break idempotence, and what are the three ways to fix it? Must-know ​

Answer

Answer: The command module cannot know whether the command changed anything, so it runs every time and reports changed, which also fires every handler it notifies. Fixes: use a real module; add creates/removes so it runs only when a file is missing or present; or set changed_when (and failed_when) from the command's output, changed_when: false for read-only commands. See Idempotence.

4 — Three tasks notify the same restart handler and a fourth task fails on host 3. What runs where? Must-know ​

Answer

Answer: On the hosts that did not fail, the handler runs once, at the end of the section (or at meta: flush_handlers), in its definition order among other handlers. On host 3 the pending handler does not run, because the host left the play; the config is new on disk but the old process keeps running, and the next run will not notify again because the template is already ok. force_handlers: true or a restart in rescue fixes it. See Handlers.

5 — A role sets nginx_workers: 4 and the team sets nginx_workers: 16 in group_vars/web.yml, but hosts keep 4. Why? Must-know ​

Answer

Answer: The role defines it in vars/main.yml, which is level 15 of the 22 precedence levels and beats every inventory variable (levels 3-10). Caller-overridable knobs belong in defaults/main.yml (level 2). Extra vars (-e, level 22) would win, but that hides the problem. See Variables and precedence.

6 — Where must secrets live in an Ansible repository, and how do they still leak? Must-know ​

Answer

Answer: In Vault-encrypted files (or SOPS, or an external store via a lookup), referenced through vault_ variables, with one vault ID per environment and the password supplied by a client script. Vault "ONLY protects 'data at rest'": after decryption, values print in --diff, -v, debug, error messages and ansible-inventory --list. Use diff: false and no_log: true on tasks that render them. See Secrets.

7 — How do you roll a config change to 40 web servers so a mistake breaks at most one? Important ​

Answer

Answer: serial: [1, "25%"] with max_fail_percentage: 0, so the play runs on one host first and stops if it fails; drain the host from the load balancer in pre_tasks, flush handlers and health-check before re-enabling it in post_tasks. Failures are counted per batch, so later batches never start. See Rolling updates.

8 — Why can --check fail on a fresh host while the real run succeeds? Important ​

Answer

Answer: Check mode is a simulation: tasks that depend on what an earlier task would have created (a directory for chdir, a symlink target, a registered result) see nothing. The lab hit it three times (src file does not exist, Unable to change directory before execution). Guard such tasks with ansible_check_mode and keep --check --diff as a supported, tested path. See Check and diff.

9 — Why is run_once the wrong way to run Laravel migrations in a play with serial? Important ​

Answer

Answer: With serial, run_once means once per batch, so two batches migrate twice (reproduced in transcript 37). Bind the task to the first host of the whole play, when: inventory_hostname == ansible_play_hosts_all[0], and make the status honest with changed_when on the "Nothing to migrate" output. The migration must also be backwards compatible with the release still serving. See Laravel.

10 — How does the Go role restart the service without refusing connections? Important ​

Answer

Answer: A systemd .socket unit owns the port and hands the listening socket to the service as file descriptor 3 (LISTEN_FDS, LISTEN_PID); during a restart the socket stays open and the kernel queues connections until the new process accepts. The old process drains on SIGTERM with http.Server.Shutdown within TimeoutStopSec. systemctl reload would not help: a Go binary has no reload without ExecReload= and a signal handler. See The Go angle.

11 — How should a CI pipeline get SSH access and the vault password for a production run? Important ​

Answer

Answer: With no stored long-lived keys: the job requests a GitHub OIDC token (id-token: write), logs in to HashiCorp Vault with JWT auth bound to the repository and environment, reads the vault password, and has Vault's SSH engine sign a fresh key with a 10-minute ttl for the deploy principal; hosts trust the SSH CA. It runs --check --diff, then applies, under an environment with required reviewers. See Ansible in CI.

12 — How do Puppet, Chef and Salt differ from Ansible in model and in how they fix drift? Good to know ​

Answer

Answer: Puppet and Chef are pull-based with an agent: Puppet's agent sends facts and applies a compiled catalog (default runinterval 30m); Chef Infra Client periodically fetches cookbooks and converges locally; both correct drift on every run. Salt keeps minions connected to a master over an event bus and can react to events (reactor). Ansible pushes on demand, so drift is fixed only when someone or a schedule runs it. See Compared.

13 — When should you not use configuration management at all? Good to know ​

Answer

Answer: For container contents (the Dockerfile owns them), for Kubernetes objects (Helm/Kustomize with Argo CD or Flux reconcile continuously), for managed cloud resources (Terraform), and for autoscaled VMs that should be replaced from an image rather than patched. CM stays for long-lived hosts: bastions, database VMs, self-managed nodes and VMs running apps directly. See When not to.

Glossary ​

TermMeaning
Configuration managementDeclaring and repeatedly converging the state of hosts
Provisioning vs configurationCreating resources via APIs (Terraform) vs setting up the inside of a host (Ansible)
Image bakingBuilding a machine or container image with configuration applied (Packer, Dockerfile)
PackerHashiCorp tool "for creating identical machine images for multiple platforms"
Immutable infrastructureServers never modified after deploy, only replaced
DriftDifference between declared and actual host state
AnsibleAgentless, push-based CM and orchestration tool (ansible-core + collections)
AgentlessNo daemon on the managed host; connections on demand
SSHDefault transport for Linux managed nodes
WinRMWindows remote management protocol used by Ansible for Windows hosts
Control nodeThe machine that runs ansible-playbook
Managed nodeA host Ansible configures
InventoryHosts, groups and their variables
Static inventoryHand-written INI or YAML inventory
Dynamic inventoryInventory built at run time from an external source
Inventory pluginsPlugins that build inventory (amazon.aws.aws_ec2, google.cloud.gcp_compute, constructed)
GroupsNamed sets of hosts; all and ungrouped always exist
group_vars / host_varsDirectories of variables per group / per host
ansible.cfgThe single configuration file Ansible reads (first match)
PlaybookYAML file with one or more plays
PlayMaps a host pattern to tasks and roles
TaskOne call of a module with arguments
ModuleCode Ansible runs on the host to do one thing idempotently
FQCNFully qualified collection name, namespace.collection.module
ansible.builtinThe collection shipped inside ansible-core
CollectionsPackages of modules, plugins and roles (community.general, ansible.posix)
ansible-galaxyCLI to install and create roles and collections
becomePrivilege escalation (default method sudo, user root)
sudoDefault become method
HandlersTasks run once at section end when notified
notify / listenQueue a handler / subscribe a handler to a topic
whenPer-host, per-task condition
loopRepeat a task over a list
registerSave a task's result in a variable
FactsHost data collected by the setup module
gather_factsPlay keyword that runs the setup module first
Setup moduleansible.builtin.setup, the fact collector
Variable precedenceThe 22-level order deciding which definition wins
Defaults vs varsRole defaults/ (lowest) vs role vars/ (level 15)
Jinja2Templating language used by Ansible, evaluated on the controller
Templates.j2 files rendered by the template module
FiltersJinja2 functions applied with a pipe (default, bool, to_json)
Template module / copy moduleWrite a rendered / a static file, only on difference
lineinfile / blockinfileManage one line / one marked block in a file
File moduleDirectories, links, modes, absence
Service module / systemd moduleManage services / systemd specifics (daemon_reload)
Package module / aptGeneric package manager / Debian-Ubuntu packages
Command vs shellNo shell (safer) vs /bin/sh with pipes and redirects
creates / removesSkip a command if a file exists / does not exist
IdempotenceRe-running changes nothing when the state is already right
ok / changed / failed / skippedPer-task, per-host result states
Check mode (--check)Dry run; modules report what they would change
Diff mode (--diff)Show before/after for changed files
Tags / --limitSelect tasks / select hosts
serial / rolling updateRun the play in batches of hosts
Strategy / free strategyTask scheduling across hosts; free lets hosts run ahead
block rescue alwaysGrouping with failure and cleanup sections
failed_when / changed_whenExpressions that define failure / change for a task
ignore_errorsContinue after a failed task (shown as ignored)
Roles / role layoutReusable folder structure: tasks, handlers, defaults, vars, templates, files, meta
Meta dependenciesRoles listed in meta/main.yml that run first, once
Argument specsmeta/argument_specs.yml input validation
Ansible VaultBuilt-in encryption for variables and files
ansible-vault encrypt / encrypt_stringEncrypt a file / one value
Vault IDLabel that ties encrypted content to a password source
SOPSEncrypted-file editor using KMS, age or PGP (community.sops)
Lookup pluginsController-side functions that fetch data (env, hashi_vault)
ansible-lintLinter with profiles (min ... production)
--syntax-checkParse-only check of a playbook
MoleculeTest framework: create, converge, idempotence, verify, destroy
Assert moduleFails unless expressions hold
AWXOpen-source web UI/API for Ansible; upstream of AAP
Ansible Automation PlatformRed Hat's supported automation product (controller, hub, EEs)
Execution environmentContainer image that acts as a control node
Chef / Chef InfraRuby-based, pull-model CM: Chef Infra Server and Client
Cookbook / recipeChef's unit of distribution / a collection of resources in Ruby
Pull modelAgents fetch desired state on a schedule
Puppet / manifestDeclarative CM / file of Puppet resources
Puppet agentDaemon that sends facts and applies catalogs (runinterval 30m)
Puppet BoltAgentless task runner over SSH/WinRM
Salt / SaltStackEvent-driven CM and remote execution; master and minions
Minion / masterSalt agent / Salt server
State (Salt)Desired-state declaration in an SLS file
Pillar / grainsPer-minion data compiled on the master / host facts
ReactorSalt subsystem mapping events to actions
Push vs pullController-initiated vs agent-initiated convergence
Agent vs agentlessDaemon per host vs on-demand connections
systemd unitA .service or .socket file systemd manages
Socket activationsystemd owns the listening socket and passes it to the service
PHP-FPMPHP FastCGI Process Manager running Laravel behind Nginx
Nginx roleThe part of the Laravel role that templates and reloads the Nginx site
SupervisorProcess control system, Laravel's documented queue worker manager
Queue workersLong-lived php artisan queue:work processes
php artisanLaravel's CLI (optimize, migrate --force, queue:restart)
DeployerPHP deploy tool with release directories and a Laravel recipe
EnvoyLaravel's Blade-syntax SSH task runner
Forge / EnvoyerLaravel's managed server service / zero-downtime deploy service
Go binary deployCopying a static Go binary into a release directory and restarting its unit

References ​

Built by Morteza Negahi