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 for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why CM exists; mutable vs immutable; the trade-offs | Why it exists |
| CFEngine 1993, Puppet, Chef 2009, Salt 2011, Ansible 2012, ansible-core | Where it comes from |
| Provisioning vs configuration, image baking, Packer, immutable infrastructure, drift | CM vs provisioning vs images vs GitOps |
| Agentless, SSH, WinRM, control node, managed node, modules | Ansible architecture |
Static inventory, dynamic inventory, inventory plugins, groups, group_vars, host_vars | Inventory |
ansible.cfg, forks, pipelining, fact caching | ansible.cfg |
Playbook, play, task, module, FQCN, ansible.builtin, collections | Playbooks |
become, sudo, become_user | Privilege escalation |
Facts, gather_facts, setup module, register, when, loop | Facts, conditions, loops |
| Variable precedence (22 levels), defaults vs vars, group merge order | Variables and precedence |
Jinja2, templates, filters, template vs lineinfile vs blockinfile | Templates |
Idempotence, ok/changed/failed, command vs shell, creates, changed_when | Idempotence |
Handlers, notify, listen, flush_handlers | Handlers |
Check mode (--check), diff mode (--diff) | Check and diff |
Tags, --tags, --limit | Tags and limits |
serial, rolling update, max_fail_percentage, strategy, free strategy | Rolling updates |
block/rescue/always, failed_when, ignore_errors | Error handling |
Roles, role layout, meta dependencies, argument specs, ansible-galaxy | Roles |
Ansible Vault, ansible-vault encrypt, vault ID, encrypt_string, SOPS, lookup plugins | Secrets |
--syntax-check, ansible-lint, Molecule, assert module | Testing |
| Running playbooks from GitHub Actions with OIDC-issued SSH certificates | Ansible in CI |
| AWX, Ansible Automation Platform, execution environments | AWX and AAP |
| Chef (cookbooks, recipes), Puppet (manifests, agent, Bolt), Salt (minions, states, pillar, grains, reactor) | Chef, Puppet, Salt |
| When not to use CM | When not to |
| Push vs pull, agent vs agentless, side by side | Compared |
| What happens when a task runs; knobs; error messages | Mechanics |
| Code | Go, Laravel |
| Classic problems and fixes | Solving the classic problems |
| Which tool, which secret store, which deploy tool | Choosing |
| From one VM to a fleet | In architecture |
| Commands with real output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary in four products.
| Concept | Ansible | Puppet | Chef Infra | Salt |
|---|---|---|---|---|
| Model | Push from a control node (ansible-pull exists, rare) | Pull: agent asks the primary server for a catalog | Pull: Chef Infra Client fetches cookbooks from Chef Infra Server | Push and pull: master publishes to minions over an event bus; salt-ssh is agentless |
| Agent on the host | None; needs SSH (or WinRM) and Python | puppet agent | chef-client | salt-minion |
| Language | YAML + Jinja2 | Puppet DSL (declarative) | Ruby DSL | YAML + Jinja (SLS files) |
| Unit of desired state | Task calling a module | Resource in a manifest | Resource in a recipe | State in an SLS file |
| Reusable package | Role, collection (Galaxy) | Module (Forge) | Cookbook (Supermarket) | Formula |
| Host facts | Facts (setup module) | Facts (Facter) | Ohai attributes | Grains |
| Per-host data and secrets | Inventory vars, Ansible Vault | Hiera | Data bags, attributes | Pillar |
| "Restart if changed" | Handler + notify | ~> / notify refresh | notifies :restart | watch / onchanges |
| Order | Top to bottom | Dependency graph (->, require) | Top to bottom | Requisites, then file order |
| Ad hoc execution | ansible all -m ... | Puppet Bolt | knife ssh | salt '*' cmd.run |
| GUI / API / RBAC | AWX, Ansible Automation Platform | Puppet Enterprise | Chef Automate | Salt master API, SaltStack Config |
What runs where in this chapter's two roles.
| Step | Go service (go_service role, orders-api) | Laravel app (laravel_app role, shop) | Lab status |
|---|---|---|---|
| 1 Base | common role (meta dependency): layout, packages, timezone | Same | Layout ran; packages expected, not run |
| 2 Account | System user orders-api, no shell | System user shop; php8.4-fpm, nginx, supervisor packages | Expected, not run |
| 3 Release | Checksummed binary into releases/1.4.2/, keep 3 releases | Git checkout + Composer into releases/<id>/, shared storage and .env | Ran (binary copied from the controller; code copied from the snippet tree) |
| 4 Config | Env file from Vault (0640, no diff), socket + service units | .env from Vault, PHP-FPM pool, Nginx site, queue worker unit or Supervisor program | Ran (files rendered under the lab root) |
| 5 Build steps | None (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 Switch | current symlink, handler restarts the service | current symlink, handlers reload PHP-FPM, Nginx and restart queue workers | Ran; service handlers are stand-ins |
| 7 Verify | uri on /healthz + assert on the version | uri on /up through Nginx | Expected, not run; file-level asserts ran |
The rules in one table.
| Rule | Why | Where |
|---|---|---|
A second run must report changed=0 | Anything else is drift you are causing yourself, and it fires handlers (restarts) for nothing | Idempotence |
Prefer a real module to command/shell; if you must, add creates or changed_when | A command always reports changed and cannot be checked in --check | Idempotence |
| Restart in handlers, never in tasks | A handler runs once, only if something changed | Handlers |
Knobs in defaults/, constants in vars/ | Role vars beat inventory; callers cannot override them | Precedence |
Secrets in Vault (or SOPS / a lookup), referenced through vault_ variables; diff: false / no_log on tasks that render them | Vault protects data at rest only; --diff and -v print values | Secrets |
Use FQCNs (ansible.builtin.copy) | No ambiguity between collections; ansible-lint enforces it | Playbooks |
serial + max_fail_percentage for anything that restarts | A bad change stops at the first batch, not at the whole fleet | Rolling updates |
--check --diff before every apply, in CI | You read the change before it happens; drift shows up as a diff | Check and diff |
| Do not configure containers with CM | Images and Kubernetes manifests already describe that state | When not to |
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 choice | Richer choice | What you buy | What you pay |
|---|---|---|---|
| SSH in and type commands | A playbook in Git | Repeatable, reviewable, auditable changes | Learning the tool; keeping tasks idempotent |
| Shell script run over SSH | Modules with declared state | Safe reruns, --check, --diff, per-task status | Less freedom than a script |
| One big playbook | Roles with defaults, handlers, tests | Reuse across services and teams | A layout and precedence rules to learn |
| All hosts at once | serial batches with a failure threshold | A bad change hits one host, not all | Longer deploys |
| Push on demand (Ansible) | Agent pulling every 30 minutes (Puppet, Chef, Salt) | Drift is corrected without anyone acting | An agent per host and a server to operate |
| Mutable hosts, configured in place | Immutable images, replaced on change | No drift, fast rollback by image | An image pipeline; state must live elsewhere |
| Plain-text vars | Ansible Vault, SOPS or an external secret store | Secrets safe in Git | Password and key distribution |
| Hand-run from a laptop | Run from CI or AWX with short-lived credentials | Audit log, no personal keys on servers | Pipeline 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
- "Ansible is idempotent." Modules can be; your playbook is idempotent only if every task is.
command,shelland acopyof a generated timestamp reportchangedevery time. The lab proves it the hard way: the second run of the first Laravel role draft reportedchanged=2on both hosts (acreatespath that never matched, and a migration command whose result could not be trusted) until both were fixed. See Idempotence and Lab. - "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-voutput and inansible-inventory --list(shown in the lab). See Secrets. - "Variables in a role are the role's defaults." Only
defaults/main.ymlis low-precedence.vars/main.ymlsits at level 15 of 22 and beats every inventory variable; a caller who sets the same name ingroup_varsis silently ignored. See Variables and precedence.
Where it comes from
| When | What happened | Source |
|---|---|---|
| 1993 | CFEngine: "The CFEngine project began in 1993" (Mark Burgess, Oslo University), the first widely used convergent CM tool | Wikipedia, CFEngine (secondary) |
| 2005 | Puppet (Luke Kanies): a declarative language compiled into catalogs that agents apply | Wikipedia, Puppet (software) (secondary); help.puppet.com |
| January 2009 | Chef (Opscode), Ruby DSL, Chef server and client | Wikipedia, Progress Chef (secondary) |
| 19 March 2011 | Salt (Thomas S. Hatch): remote execution over a message bus, then states | Wikipedia, Salt (software) (secondary) |
| 2012 | Ansible, "Originally written by Michael DeHaan in 2012", agentless over SSH | Wikipedia, Ansible (software) (secondary) |
| 16 October 2015 | "Red Hat to Acquire IT Automation and DevOps Leader Ansible" | Red Hat press release |
| After 2.9 | The 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 2023 | ansible-core 2.15 GA; 2.15.13 (4 Nov 2024) is the last 2.15 release, end of life Nov 2024 | Ansible Releases and maintenance; 2.15 changelog |
| May 2026 | ansible-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 |
| 2026 | Chef Infra Client 19 docs, Puppet Core 9.1.4 ("Last published: November 19, 2026"), Molecule's "ansible-native" configuration alongside the older driver model | docs.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
| Line | GA | End of life | Control node Python | Target Python | Used here |
|---|---|---|---|---|---|
| 2.15 | 22 May 2023 | Nov 2024 | 3.9-3.11 | 2.7, 3.5-3.11 | The lab (2.15.13), because the build machine has CPython 3.9.6 only |
| 2.20 | 03 Nov 2025 | May 2027 | 3.12-3.14 | 3.9-3.14 | |
| 2.21 | May 2026 | Nov 2027 | 3.12-3.14 | 3.9-3.14 | Recommended pin in the CI workflow |
| 2.22 | Nov 2026 | May 2028 | 3.13-3.15 | 3.9-3.15 | Current 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."
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 themReal scenarios:
- A team runs Ansible against 40 Ubuntu VMs every night in
--check --diffmode and pages nobody; the report shows that 3 hosts have a hand-editedsshd_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.
| Layer | Tool family | Talks to | Keeps state? | Typical products |
|---|---|---|---|---|
| Cloud resources | Provisioning | Cloud/provider APIs | Yes (state file) | Terraform, OpenTofu, Pulumi, CloudFormation, CDK |
| Machine image | Image baking | Hypervisor / cloud image API, then the OS during build | Image versions | Packer, EC2 Image Builder |
| Container image | Image baking | BuildKit | Registry digests | Docker, BuildKit, Buildah |
| Host inside | Configuration management | SSH/WinRM, or an agent on the host | No (Ansible); last report (Puppet/Chef) | Ansible, Puppet, Chef, Salt, CFEngine |
| Kubernetes objects | GitOps | Kubernetes API | Git + cluster | Argo 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,winrmandpsrpfor Windows,local(run on the control node itself, used by this chapter's lab),dockerandcommunity.docker.dockerfor containers,kubernetes.core.kubectl,amazon.aws.aws_ssmfor 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: winrmand authentication such as NTLM, Kerberos or CredSSP.
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 taskReal scenarios:
- A minimal Debian cloud image has no Python: the first task fails with a module error until a
raw: apt-get install -y python3bootstrap 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.
| Requirement | Ansible | Puppet | Chef Infra | Salt |
|---|---|---|---|---|
| Daemon on the host | No | puppet agent | chef-client (daemon or timer) | salt-minion (none with salt-ssh) |
| Transport | SSH, WinRM/PSRP, local, docker, SSM | HTTPS to the primary server (8140) | HTTPS to Chef Infra Server | ZeroMQ to the master (4505/4506); SSH for salt-ssh |
| Trust bootstrap | SSH key or certificate + sudo rule | Agent certificate signed by the Puppet CA | Client key registered with the server | Minion key accepted on the master |
| Interpreter on the host | Python (or PowerShell) | Bundled Ruby in the agent package | Bundled Ruby in the client package | Bundled 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_ec2andgoogle.cloud.gcp_computeread a YAML config (the file name must match what the plugin expects, for example ending inaws_ec2.yml), call the API, and build groups from tags withkeyed_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_prioritysays otherwise.
The lab inventory, four aliases on one machine:
# 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:# 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/allThe 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.
# 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# 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# 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.prodReal scenarios:
- An autoscaling group replaces VMs daily; a static file is wrong within hours. The
aws_ec2plugin withkeyed_groupson theRoletag always targets what is running. - A host is accidentally tagged both
Env=stagingandEnv=productionand 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'ingroup_vars/production.yml(see VPNs & Tunnels).
| Inventory source | How it is enabled | Good for | Watch out |
|---|---|---|---|
| INI file | Default (ini plugin) | Small, stable fleets | Values are strings unless declared in YAML vars files |
| YAML file | Default (yaml plugin) | Nested groups, typed vars | Indentation; hosts: entries need a trailing colon |
amazon.aws.aws_ec2 | Collection + boto3; file *.aws_ec2.yml | EC2 fleets, autoscaling | API rate limits: enable cache: true |
google.cloud.gcp_compute | Collection + google-auth; file ending gcp_compute.yml or gcp.yml | GCE fleets | Labels vs tags naming |
constructed | Built-in | Groups from existing vars (keyed_groups, groups) | Runs after the sources it reads |
| Inventory script | Executable printing --list JSON | Legacy CMDBs | Slower; no caching or composition |
| A directory of the above | -i inventories/production | One environment = one directory | Files 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.
# 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=60swhich 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 bothReal scenarios:
- A run against 300 hosts takes 40 minutes with the default 5 forks and 6 minutes with
forks = 50and pipelining on. pipelining = Truebreaksbecomeon hosts whose sudoers still hasrequiretty(sudo refuses to run without a terminal); the fix is the sudoers default (Defaults !requiretty), not turning pipelining off.host_key_checking = Falsecopied from a blog post lets a man-in-the-middle answer for a production host; CI should ship aknown_hosts(or an SSH CA line) instead.
| Setting | Default | Why change it |
|---|---|---|
forks | 5 | Hosts in flight per task; raise for fleets |
pipelining | False | Fewer SSH round trips; needs no requiretty |
ssh_args | -C -o ControlMaster=auto -o ControlPersist=60s | Keep multiplexing; add ProxyJump per group instead |
host_key_checking | True | Keep it True; distribute host keys or an SSH CA |
gathering | implicit | smart + a fact cache avoids re-gathering |
fact_caching | memory | jsonfile or redis to keep facts between runs |
interpreter_python | auto | auto_silent hides the discovery warning |
callbacks_enabled | none | ansible.posix.profile_tasks for per-task timings |
vault_identity_list | none | Default vault IDs, for example prod@scripts/vault-pass.sh |
retry_files_enabled | False | Keep 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:
# 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# 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"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 hostReal scenarios:
- Two collections ship a module called
docker_container; with short names, the one found first wins. Withcommunity.docker.docker_containerthere is no question. - A role written for Ansible 2.9 uses
apt:andservice:short names; it still works through theansible.builtinredirect, but ansible-lint'sfqcnrule flags every line. - Upgrading
community.generalfrom 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 for | Instead 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 Jinja2 | copy + lineinfile edits |
ansible.builtin.file (file module) | Directories, symlinks, modes, state: absent | mkdir -p, ln -s, rm -rf |
ansible.builtin.lineinfile / blockinfile | One line or one marked block in a file you do not own | Templating a whole distro file |
ansible.builtin.package (package module) | Packages with the host's package manager | apt/dnf when the role is cross-distro |
ansible.builtin.apt | Debian/Ubuntu packages, update_cache, cache_valid_time | command: apt-get install |
ansible.builtin.service (service module) | Start, stop, reload, enable, any init system | command: systemctl ... |
ansible.builtin.systemd_service (systemd module; systemd is an alias) | systemd specifics: daemon_reload, masked units, scope | command: systemctl daemon-reload |
ansible.builtin.user / group | Accounts | useradd |
ansible.builtin.git | Checking out a release | command: git clone |
ansible.builtin.get_url | Download with checksum: | curl in shell |
ansible.builtin.uri | HTTP checks, API calls | curl in shell |
ansible.builtin.assert (assert module) | Fail with a message unless conditions hold | fail + when |
ansible.builtin.command / shell | Only when no module exists | - |
community.general.supervisorctl, community.general.composer, community.general.timezone | Supervisor programs, Composer, timezone | command: |
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.
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: ALLis convenient and means the deploy key is root on every host; narrow it, or use short-lived SSH certificates (Ansible in CI). become_user: postgresforpsqltasks fails with "Failed to set permissions on the temporary files" untilaclis installed or pipelining is on.becomeset globally inansible.cfgmakes everycopycreate 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.
# 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'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=1Real scenarios:
- A role installs
php8.4-fpmwithansible.builtin.packageonlywhen: ansible_facts['os_family'] == 'Debian', and a separate task for RedHat. - Fact gathering on 2,000 hosts takes minutes per run;
gathering = smartplus a Redis fact cache with a 24-hour timeout cuts it to the first run of the day. - A
registeredcommandresult is used inwhenunder--check: the command was skipped in check mode, so the condition sees nostdout("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 |
|---|---|---|---|
| 1 | Command-line values (-u my_user; "these are not variables") | 12 | Play vars |
| 2 | Role defaults (defaults/main.yml) | 13 | Play vars_prompt |
| 3 | Inventory file or script group vars | 14 | Play vars_files |
| 4 | Inventory group_vars/all | 15 | Role vars (vars/main.yml) |
| 5 | Playbook group_vars/all | 16 | Block vars |
| 6 | Inventory group_vars/* | 17 | Task vars |
| 7 | Playbook group_vars/* | 18 | include_vars |
| 8 | Inventory file or script host vars | 19 | Registered vars and set_fact |
| 9 | Inventory host_vars/* | 20 | Role (and include_role) params |
| 10 | Playbook host_vars/* | 21 | Include params |
| 11 | Host facts and cached set_fact | 22 | Extra 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."
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/productionran: 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 22Real scenarios:
- A role sets
nginx_worker_processes: 4invars/main.yml; ops setnginx_worker_processes: 16ingroup_vars/web.ymland nothing happens. Move it todefaults/. - A host in
euandproductiongetsntp_serverfrom whichever group sorts later;ansible_group_priority: 10oneumakes the intent explicit. - A hotfix run with
-e orders_api_version=1.4.3deploys 1.4.3, and the next scheduled run without-equietly 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.
# {{ 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# {{ 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-fulltemplate 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 handlerReal scenarios:
sshd_configis templated withvalidate: /usr/sbin/sshd -t -f %s, so a typo never replaces the live file and locks everyone out.- A team uses
lineinfileto setmemory_limitinphp.ini; a package upgrade ships a newphp.iniwith 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 useansible_managedwithout a date for this reason.
| Module | Owns | Idempotent when | Use for |
|---|---|---|---|
ansible.builtin.template | The whole file | Rendered text is stable | Files you own: units, app config, vhosts |
ansible.builtin.copy | The whole file | Source bytes are stable | Static files, binaries, content: one-liners |
ansible.builtin.lineinfile | One line (by regexp) | regexp matches what line writes | One setting in a distro file (/etc/sysctl.conf) |
ansible.builtin.blockinfile | A block between marker lines | Markers are unique | A fragment in a file others also edit (/etc/hosts) |
ansible.builtin.replace | Every match of a regex | The replacement does not match the regex again | Bulk edits |
community.general.ini_file | One key in one INI section | Always | INI 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." Prefercommand(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".
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=0Real scenarios:
shell: curl -sL https://example.com/install.sh | bashruns the installer on every deploy, re-downloads a moving target, and cannot be checked. Useget_urlwithchecksum:plusunarchive, or a package.php artisan migrate --forcereportschangedevery run, so anotify: restart queue workersrestarts every worker on every deploy, even when no migration ran.changed_whenon the "Nothing to migrate" line fixes the status (Laravel).- A
command: useradd shopfails on the second run ("user already exists");ansible.builtin.useris idempotent.
| Task | Run 1 | Run 2 | Fix |
|---|---|---|---|
ansible.builtin.file: state=directory | changed | ok | None needed |
ansible.builtin.template | changed | ok | Keep templates stable |
ansible.builtin.command: php artisan optimize | changed | changed | creates: <release>/bootstrap/cache/config.php (absolute; a relative path is resolved inside chdir) |
ansible.builtin.command: php artisan migrate --force | changed | changed | changed_when on the output |
ansible.builtin.command: uname -s (read-only) | changed | changed | changed_when: false |
ansible.builtin.shell: apt-get install -y nginx | changed | changed | ansible.builtin.apt: name=nginx state=present |
ansible.builtin.copy: content="{{ now() }}" style | changed | changed | Do not template run-time values |
block + rescue that writes v2 then v1 back | changed | changed | Validate 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.
# 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 restartran: --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 firstReal scenarios:
- A unit file and its env file both change;
daemon-reloadmust happen beforerestart, 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: trueor an explicit restart inrescuecloses the gap. - A health check after a restart must see the new process:
meta: flush_handlersbefore theuritask.
| Feature | Ansible | Puppet | Chef | Salt |
|---|---|---|---|---|
| Restart on change | notify + handler | notify / ~> (refresh) | notifies :restart, ..., :delayed | watch: / onchanges: |
| Runs once per run | Yes | Yes (one refresh per resource) | :delayed queues once | Yes |
| Run now | meta: flush_handlers | (graph order) | :immediately | listen / 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).
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- 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 --diffagainst production prints a diff for one host's Nginx site: somebody hot-fixed it by hand. The diff is the drift report. --checkon 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
--diffrun of a task that renders.envprintsDB_PASSWORD=...into the CI log.diff: false(used in both roles) orno_log: trueprevents 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.
# 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=2Real scenarios:
- A config-only hotfix (
--tags config) to 30 hosts finishes in a minute because releases, packages and users are skipped. --limit orders-1.prodis the canary step done by hand;serial: [1, ...]is the same idea automated.- The
alwaystag on the load-balancer drain and enable tasks insite.ymlkeeps a--tags configrun 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.
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 untouchedReal scenarios:
- 12 web servers behind a load balancer:
serial: [1, "25%", "100%"]gives a canary, then quarters, then the rest;max_fail_percentage: 0stops at the canary. - A package mirror update across 500 hosts with no ordering needs:
strategy: freeandforks: 100let fast hosts finish without waiting for slow ones. - A cache warm-up endpoint that can take one request at a time:
throttle: 1on that task only.
| Keyword | Scope | Default | Effect |
|---|---|---|---|
forks | Config / CLI -f | 5 | Parallel hosts per task |
serial | Play | All hosts | Batches; failures counted per batch |
max_fail_percentage | Play | (100) | Abort when exceeded within a batch |
any_errors_fatal | Play / block | false | Any failure stops every host |
strategy | Play / config | linear | free, debug, host_pinned |
throttle | Task / block | forks | Max workers for that task |
run_once | Task | false | First host of the batch; result applied to all |
order | Play | inventory | Host 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".
# 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: falseran: 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,
rescuerestores the previouscurrentsymlink and notifies a restart: an automated rollback per host. grep,diffandsystemctl is-activeuse 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);
alwaysreleases 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.
# 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# 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 writtengalaxy_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# 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- 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]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 flushedReal scenarios:
- Three teams copy the same 200-line "install nginx" task list into their playbooks; one role with
defaultsfor ports and worker counts replaces all three. - A caller passes
orders_api_verison(typo): without argument specs the role silently deploys the default0.0.0; with them, the play fails before any task. include_rolewithloopdeploys five similar services from one role, each with its own variables.
| Folder / file | Purpose | Precedence of vars there |
|---|---|---|
defaults/main.yml | Knobs a caller may override | Level 2 (lowest that is a variable) |
vars/main.yml | Internal constants | Level 15 (beats inventory and play vars) |
tasks/main.yml | Entry point; include_tasks/import_tasks for the rest | - |
handlers/main.yml | Notified tasks | - |
templates/ | .j2 files for the template module | - |
files/ | Static files for the copy module | - |
meta/main.yml | galaxy_info, dependencies | - |
meta/argument_specs.yml | Input 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_stringon 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.ymlasvault_db_password, and reference them from a plainvars.ymlasdb_password: "{{ vault_db_password }}", sogrepstill 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.sopscollection (a vars plugin and theload_varsmodule); lookup plugins that fetch at run time, such ascommunity.hashi_vault.hashi_vault,amazon.aws.aws_secretandansible.builtin.env.
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#!/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"# 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
--diffon in a CI job that templates.env; the database password is in the build log for 90 days.diff: falseon 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.
| Option | Where the secret lives | Decrypted by | Good for | Cost |
|---|---|---|---|---|
| Ansible Vault files | Git, encrypted with a password | ansible-core | Small teams, no external dependency | One shared password to distribute and rotate |
encrypt_string values | Git, inline !vault | ansible-core | One secret in an otherwise plain file | Harder to diff and rotate |
SOPS + community.sops | Git, encrypted per value with KMS/age | sops binary + cloud KMS | Per-environment keys, IAM-controlled decryption | KMS setup |
| Lookup plugins (HashiCorp Vault, AWS Secrets Manager) | External store | The lookup, at run time, on the controller | Rotation, audit, no secret in Git | Network dependency during runs |
| CI secret / OIDC-fetched | CI or external store | The pipeline | Vault password itself | Pipeline 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...); thenmoderate,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_sequenceis "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 aswhen.
# 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# 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- 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'# 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: truemolecule 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=0Real scenarios:
- A pull request adds
shell: systemctl restart nginxto 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.
| Layer | Tool | Catches | Speed |
|---|---|---|---|
| Parse | ansible-playbook --syntax-check, YAML parser | Bad YAML, unknown modules in static tasks, missing roles | Seconds |
| Rules | ansible-lint (profile production) | Free-form commands, missing names, non-FQCN modules, risky permissions | Seconds |
| Inventory | ansible-inventory --list + a checker (Go) | Missing vars, hosts in two environments, plaintext secrets | Seconds |
| Behaviour | Molecule (Docker, Podman, or delegated VMs) | Real failures, non-idempotent tasks | Minutes |
| End state | assert, stat, uri in a verify playbook | Wrong modes, wrong symlink, service not answering | Seconds to minutes |
| Dry run | --check --diff against the real inventory | What would change in production | Minutes |
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.
# .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# 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>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 runnerReal 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 --diffoutput 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.
| Need | Plain CLI + CI | AWX / AAP |
|---|---|---|
| Who ran what, when | CI logs | Job history, per-user RBAC |
| Credentials | CI secrets / OIDC | Credential store, external lookups |
| Schedules (drift correction) | CI cron | Built-in schedules |
| Self-service ("restart orders-api") | Workflow dispatch | Job templates with surveys |
| Same toolchain everywhere | Pinned pip + requirements.yml | Execution 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.
# 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]
endFix / 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: 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.
# 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# 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 configure | Owner | Why not CM |
|---|---|---|
| Container contents (packages, PHP extensions, the Go binary) | Dockerfile / image build | Built once, scanned, signed; Images & Dockerfiles |
| Kubernetes Deployments, ConfigMaps, Secrets | Helm/Kustomize + Argo CD or Flux | Continuous reconciliation, drift visible in the UI |
| Managed services (RDS, Cloud SQL, load balancers) | Terraform | Provider API with a state file and a plan |
| Kubernetes nodes on a managed service (EKS, GKE) | The provider's node images | Replaced, not patched |
| Self-managed nodes (kubelet, containerd, kernel settings), bastions, VPN gateways, database VMs, CI runners | Ansible (or Puppet/Chef/Salt) | Long-lived hosts that drift |
| VMs that run the app directly (this chapter's two roles) | Ansible | Exactly the use case |
Compared: push vs pull, agent vs agentless
| Axis | Ansible | Puppet | Chef Infra | Salt |
|---|---|---|---|---|
| Push vs pull | Push (ansible-pull rare) | Pull (agent, runinterval 30m) | Pull (client, periodic) | Both (master publish; minion schedule; reactor) |
| Agent vs agentless | Agentless (SSH, WinRM) | Agent + primary server | Agent + Chef Infra Server | Minion + master; salt-ssh agentless |
| Language | YAML + Jinja2 | Puppet DSL | Ruby DSL | YAML + Jinja (SLS) |
| State model | Ordered tasks, idempotent modules | Declarative catalog graph | Ordered resources in Ruby | Declarative states with requisites |
| Drift correction | Only when run (schedule it) | Every run of the agent | Every client run | Schedules, beacons, reactor |
| Secrets | Vault, SOPS, lookups | Hiera eyaml, Sensitive type | Encrypted data bags, Chef Vault | Pillar (GPG renderer) |
| Testing | ansible-lint, Molecule | PDK, rspec-puppet, Litmus | Cookstyle, Test Kitchen, InSpec | salt-lint, Kitchen-Salt |
| Scale pattern | Forks, serial, AWX job slicing | Compile servers, PuppetDB | Server clusters, Policyfiles | Syndic, multi-master |
| Learning curve | Lowest | Medium (DSL + graph) | Highest (Ruby) | Medium (many subsystems) |
| Best at | Orchestrated deploys, rolling changes, ad hoc | Continuous compliance on large fleets | Ruby shops, complex logic | Fast remote execution, event-driven ops |
Mechanics
What happens when one task runs on one host
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
| Step | What runs | Handlers flushed after |
|---|---|---|
| 1 | Variables loaded; vars_files, vars_prompt | - |
| 2 | gather_facts (setup module) unless false | - |
| 3 | pre_tasks | Yes |
| 4 | roles: (dependencies first, each role once) | - |
| 5 | tasks: | Yes (with roles) |
| 6 | post_tasks | Yes |
| 7 | Next serial batch from step 2 | - |
| 8 | Next play | - |
Knobs
| Knob | Where | Effect |
|---|---|---|
-i, --inventory | CLI | Inventory source (file, directory, plugin config) |
-l, --limit | CLI | Host pattern subset |
-t, --tags / --skip-tags | CLI | Task selection by tag |
-C, --check / -D, --diff | CLI | Dry run / show changes |
-e, --extra-vars | CLI | Level 22 variables (@file.yml loads a file) |
-f, --forks | CLI / forks | Parallel hosts |
-b, --become; -K | CLI | Escalate; ask for the become password |
--vault-id, --ask-vault-pass | CLI | Vault secrets |
--syntax-check, --list-tasks, --list-tags, --list-hosts | CLI | Static inspection |
--start-at-task, --step | CLI | Resume or step through |
-v ... -vvvv | CLI | Verbosity; -vvv shows SSH commands, -vvvv connection debugging |
serial, max_fail_percentage, any_errors_fatal, strategy, order | Play | Rolling behaviour |
throttle, run_once, delegate_to, local_action | Task | Placement and concurrency |
check_mode, diff, no_log | Task | Per-task mode overrides |
ansible_connection, ansible_host, ansible_user, ansible_port, ansible_python_interpreter, ansible_ssh_common_args | Inventory vars | How to reach a host |
ansible_group_priority | Group var | Merge order for same-depth groups |
Error messages you will actually see
| Message (verbatim from the lab transcripts) | Cause | Fix |
|---|---|---|
src file does not exist, use "force=yes" if you really want to create the link | file: 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 directory | command 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 path | ansible-galaxy collection install -r requirements.yml |
The task includes an option with an undefined variable. The error was: 'orders_api_prot' is undefined | Typo or a variable from a role that is not in scope | Fix the name; argument_specs; default() only for real optionals |
ERROR! Attempting to decrypt but no vault secrets found | Encrypted vars and no --vault-id | Pass the vault ID or password file |
ERROR! Decryption failed (no vault secrets were found that could decrypt) | Wrong password for that vault ID | Correct 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 missing | ansible_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 available | Every file in the inventory directory was skipped or failed: hosts.ini is ignored by extension, plugin configs whose collection is missing fail | Name the INI file hosts; install the collections; keep plugin configs where credentials exist |
NO MORE HOSTS LEFT | Every host of the batch failed or max_fail_percentage was exceeded | Read the first fatal: above it |
non-zero return code | command/shell exited non-zero | failed_when if that exit code is fine |
...ignoring | ignore_errors: true swallowed a failure | Visible 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
# 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
doneEvery 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:
# {{ ansible_managed }}
[Unit]
Description=orders-api listening socket
[Socket]
ListenStream={{ orders_api_listen }}
NoDelay=true
[Install]
WantedBy=sockets.target# 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 }}"# 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// 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
}// 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
}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:
// 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
}
}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")
}
}// 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)
}
}module academy/configuration-management-ansible
go 1.24The lab runner that builds the binary the role deploys and runs every command against the lab:
#!/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" "$@" ;;
esacThe 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'sfileoutput: "ELF 64-bit LSB executable, x86-64 ... statically linked"); the role copies it intoreleases/<version>/, which makes rollback a symlink flip (-e orders_api_version=1.4.1). In production,get_urlwithchecksum: 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 hasExecReload=(orType=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.socketowningListenStream=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 setsLISTEN_PID/LISTEN_FDS. During a restart the socket stays open and the kernel queues new connections until the new process callsAccept; nothing is refused.activation.Listenerimplements the check from sd_listen_fds(3) with the standard library only (os.NewFile(3)+net.FileListener), falling back tonet.Listenwhen not activated (the lab run: "serving on listen 127.0.0.1:18089").github.com/coreos/go-systemd/activationdoes the same if you prefer a dependency. - Graceful drain. systemd sends
SIGTERMon stop and restart;signal.NotifyContext+http.Server.Shutdowndrains in-flight requests within 20 s, belowTimeoutStopSec=30after which systemd sendsSIGKILL. 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 withEnvironmentFile=, and the program refuses to start withoutORDERS_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_handlersthe role polls/healthzwithuri+until/retriesandasserts 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.
inventorycheckreads the merged inventory (ansible-inventory --listalready applied group_vars, host_vars and plugins), fails on missing required variables, hosts in bothstagingandproduction, and secret-looking variables that are neither!vaultvalues nor{{ vault_* }}references. It skipsvault_*names because, with a vault password,ansible-inventoryprints 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
# 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 themAfter
- 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]- 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 workerslaravel_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# 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# 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# {{ 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; {{ 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# {{ 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;
}
}# {{ 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; {{ 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.logThe 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
// 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
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');
});
}
};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-1The Laravel angle
- Atomic switch. Nginx's
root .../current/publicwithfastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_nameresolves 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 (handlerlaravel config changed) only when.envchanges. The lab found the trap:createsis resolved insidechdir, so a path written relative to anywhere else never matches and the task runs every time (transcript 38). - Migrate once.
php artisan migrate --forceruns on the first host of the whole play (ansible_play_hosts_all[0]), not withrun_once, because the play is batched withserial: "50%"andrun_oncemeans once per batch (transcript 37).changed_when: "'Nothing to migrate' not in ..."gives an honest status, sonotifyfires 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 unitshop-queue@.service(Restart=always, instances@1..@N) or Supervisor withnumprocs(Laravel's documented setup). Laravel also saysstopwaitsecsmust exceed your longest job; the same applies toTimeoutStopSecin the systemd unit. .envfrom Vault, shared across releases; the right owner. Rendered once intoshared/.env(root:shop,0640,diff: false) so theshopFPM pool and workers can read it but not change it, and linked into each release;shared/storageis owned byshop. Git, Composer and everyphp artisantask run withbecome_user: shop, so caches and compiled views are never root-owned (inert in the lab, wherebecomeis false).APP_KEYcomes from avault_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
Hostheader.
| Tool | What it is | Model | Server setup | Zero-downtime releases | When to pick it |
|---|---|---|---|---|---|
| Ansible role (this chapter) | General CM | Push over SSH | Yes (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, PHP | dep 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 syntax | Push over SSH | No | Only what your tasks script | Small task runner next to the app |
| Laravel Forge | "a server management and application deployment service" | SaaS, provisions and deploys | Yes, managed | Deploy scripts (Envoyer integration) | You want servers managed for you |
| Envoyer | "Zero downtime PHP deployment" SaaS | SaaS push | No | Yes | Deploys only, servers exist |
| Laravel Cloud | "a fully-managed Laravel platform" | PaaS | Not your concern | Platform-managed | No servers at all |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Second run reports changes | Idempotent tasks | Modules over commands; creates, changed_when; stable templates | Restarts only on real change; drift visible | Discipline; tests (Molecule idempotence) |
| A hand edit lives on for months | Drift detection | Nightly --check --diff from CI or AWX; or an agent-based tool | Changes outside Git show up | Someone must read the report |
| Bad config takes the fleet down | Rolling update with a canary | serial: [1, "25%"], max_fail_percentage: 0, drain/enable in pre/post tasks | Blast radius of one host | Slower deploys |
| Restart drops connections | Socket activation or a drain | .socket unit owns the port (Go); reload for PHP-FPM and Nginx; LB drain | No refused requests | Program must accept an inherited socket |
| Secrets in Git or logs | Vault/SOPS + no_log | vault_ indirection, diff: false, no_log: true, password from a client script | Safe at rest and in logs | Key distribution and rotation |
| Variable silently ignored | Precedence hygiene | Knobs in defaults/, constants in vars/, argument_specs, ansible-inventory --host | Predictable values | A rule everyone must know |
| Same role, many environments | Inventories per environment | inventories/<env>/group_vars, one vault ID per environment | No per-environment code | Directory sprawl |
| Migrations run on every web server | One host, once | when: inventory_hostname == ansible_play_hosts_all[0] (not run_once with serial) | One migration per deploy | Must be backwards compatible |
--check fails on a fresh host | Check-mode-aware roles | force: "{{ ansible_check_mode }}"-style arguments, when: not ansible_check_mode on dependent commands | Dry runs work everywhere | Dry run predicts less |
| Personal SSH keys on servers | CI-only access with short-lived certificates | OIDC to HashiCorp Vault, SSH CA, 10-minute ttl | Nothing to revoke when a laptop is lost | Vault and SSH CA to run |
| Slow runs on big fleets | Fewer round trips | forks, pipelining, ControlPersist, fact cache, strategy: free where order does not matter | Minutes instead of an hour | Higher controller load |
| "Works on my laptop" Ansible | Pinned toolchain | ansible-core range in CI, requirements.yml, execution environments | Same result everywhere | Upgrades 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Cloud resources (VPC, VM, DNS, IAM) | Terraform / OpenTofu | Tag VMs for the dynamic inventory | Provider APIs, plan, state |
| Autoscaled stateless VMs | Packer image (Ansible as the provisioner) | Replace, never patch | Immutable, no drift |
| Long-lived VMs running apps (this chapter's roles) | Ansible | serial, Vault, Molecule | Orchestrated, rolling deploys |
| Thousands of servers with compliance baselines | Puppet (or Chef) | Reports, PuppetDB, Hiera | Continuous enforcement |
| Fleet-wide remote execution in seconds, event-driven remediation | Salt | Reactor, beacons | Persistent bus |
| Applications in Kubernetes | Helm/Kustomize + Argo CD or Flux | ESO for secrets | Continuous reconciliation |
| Windows servers | Ansible over WinRM/SSH, or DSC | ansible.windows collection | No agent needed |
Which Ansible tool for the job
| Need | Tool | Note |
|---|---|---|
| One-off command on many hosts | ansible <pattern> -m <module> -a ... | Ad hoc; use a module, not shell |
| Repeatable change | Playbook + roles | In Git, reviewed |
| Reuse across repositories | Collection with roles | Versioned on Galaxy or a private hub |
| Run from a pipeline | CI job with pinned ansible-core | OIDC for credentials |
| Self-service, RBAC, schedules | AWX / Ansible Automation Platform | Execution environments |
| Test a role | Molecule + ansible-lint | Idempotence step |
Which secret store
| Team / platform | Choice | Why |
|---|---|---|
| Small team, no cloud KMS | Ansible Vault files, one ID per environment | Zero dependencies |
| AWS/GCP/Azure shop | SOPS with KMS (community.sops) or the cloud secret manager via lookup | IAM decides who decrypts |
| HashiCorp Vault already in place | community.hashi_vault lookup + Vault-issued SSH certificates | Rotation, audit, short-lived credentials |
| Kubernetes workloads | External Secrets Operator / sealed secrets | Different problem; not CM |
Which Laravel deploy tool
| Situation | Choice |
|---|---|
| You manage the servers and other stacks too | Ansible role (this chapter) |
| PHP team, servers already configured, want a ready recipe | Deployer |
| A few commands over SSH from the repo | Laravel Envoy |
| You want servers provisioned and managed by a service | Laravel Forge (+ Envoyer for zero-downtime deploys) |
| No servers | Laravel 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:
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 unchangedService-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
| Scale | Hosts | What changes |
|---|---|---|
| 1x | 2-10 | One repository, static inventory, Vault file, runs from CI; serial once you have two web servers |
| 10x | 50-500 | Dynamic 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 |
| 100x | 5,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)
$ 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 app22. Dry run on an empty tree, then two real runs (ran)
$ 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)
$ 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)
$ 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)
$ 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)
# 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 OK7. Molecule and ansible-lint (expected, not run)
$ 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 passCommon misconceptions
| Belief | Reality |
|---|---|
| "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
| Topic | Remember |
|---|---|
| Layers | Terraform creates, Packer/Dockerfile bakes, Ansible configures, Argo CD/Flux reconciles |
| Architecture | Control node pushes modules over SSH/WinRM; managed nodes need Python; no agent |
| Inventory | Static INI/YAML or plugins (amazon.aws.aws_ec2); all, ungrouped; group_vars, host_vars |
| Config | One ansible.cfg wins; forks 5 default; pipelining off by default; keep host key checking on |
| Modules | FQCN always; real module over command over shell |
| Idempotence | Second run changed=0; creates, changed_when; Molecule idempotence |
| Handlers | Once, definition order, end of section; listen; flush_handlers before health checks |
| Precedence | 22 levels; defaults lowest, -e highest; role vars/ beats inventory |
| Templates | Template 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 |
| Rolling | serial: [1, "25%"], max_fail_percentage: 0, drain/enable with always tag |
| Errors | block/rescue/always; failed_when over ignore_errors |
| Roles | defaults vs vars; meta dependencies run once; argument_specs |
| Secrets | vault_ indirection, vault IDs per env, password client script, or SOPS/lookups |
| Testing | --syntax-check, ansible-lint (production profile), Molecule, verify with assert |
| CI | OIDC to a secret store, short-lived SSH certificates, check then apply, one concurrency group |
| Go role | Release dirs, checksummed binary, env file 0640, socket unit + SIGTERM drain, /healthz assert |
| Laravel role | Shared .env/storage, optimize per release, migrate once, current symlink, FPM reload, queue:restart |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Configuration management | Declaring and repeatedly converging the state of hosts |
| Provisioning vs configuration | Creating resources via APIs (Terraform) vs setting up the inside of a host (Ansible) |
| Image baking | Building a machine or container image with configuration applied (Packer, Dockerfile) |
| Packer | HashiCorp tool "for creating identical machine images for multiple platforms" |
| Immutable infrastructure | Servers never modified after deploy, only replaced |
| Drift | Difference between declared and actual host state |
| Ansible | Agentless, push-based CM and orchestration tool (ansible-core + collections) |
| Agentless | No daemon on the managed host; connections on demand |
| SSH | Default transport for Linux managed nodes |
| WinRM | Windows remote management protocol used by Ansible for Windows hosts |
| Control node | The machine that runs ansible-playbook |
| Managed node | A host Ansible configures |
| Inventory | Hosts, groups and their variables |
| Static inventory | Hand-written INI or YAML inventory |
| Dynamic inventory | Inventory built at run time from an external source |
| Inventory plugins | Plugins that build inventory (amazon.aws.aws_ec2, google.cloud.gcp_compute, constructed) |
| Groups | Named sets of hosts; all and ungrouped always exist |
| group_vars / host_vars | Directories of variables per group / per host |
| ansible.cfg | The single configuration file Ansible reads (first match) |
| Playbook | YAML file with one or more plays |
| Play | Maps a host pattern to tasks and roles |
| Task | One call of a module with arguments |
| Module | Code Ansible runs on the host to do one thing idempotently |
| FQCN | Fully qualified collection name, namespace.collection.module |
| ansible.builtin | The collection shipped inside ansible-core |
| Collections | Packages of modules, plugins and roles (community.general, ansible.posix) |
| ansible-galaxy | CLI to install and create roles and collections |
| become | Privilege escalation (default method sudo, user root) |
| sudo | Default become method |
| Handlers | Tasks run once at section end when notified |
| notify / listen | Queue a handler / subscribe a handler to a topic |
| when | Per-host, per-task condition |
| loop | Repeat a task over a list |
| register | Save a task's result in a variable |
| Facts | Host data collected by the setup module |
| gather_facts | Play keyword that runs the setup module first |
| Setup module | ansible.builtin.setup, the fact collector |
| Variable precedence | The 22-level order deciding which definition wins |
| Defaults vs vars | Role defaults/ (lowest) vs role vars/ (level 15) |
| Jinja2 | Templating language used by Ansible, evaluated on the controller |
| Templates | .j2 files rendered by the template module |
| Filters | Jinja2 functions applied with a pipe (default, bool, to_json) |
| Template module / copy module | Write a rendered / a static file, only on difference |
| lineinfile / blockinfile | Manage one line / one marked block in a file |
| File module | Directories, links, modes, absence |
| Service module / systemd module | Manage services / systemd specifics (daemon_reload) |
| Package module / apt | Generic package manager / Debian-Ubuntu packages |
| Command vs shell | No shell (safer) vs /bin/sh with pipes and redirects |
| creates / removes | Skip a command if a file exists / does not exist |
| Idempotence | Re-running changes nothing when the state is already right |
| ok / changed / failed / skipped | Per-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 / --limit | Select tasks / select hosts |
| serial / rolling update | Run the play in batches of hosts |
| Strategy / free strategy | Task scheduling across hosts; free lets hosts run ahead |
| block rescue always | Grouping with failure and cleanup sections |
| failed_when / changed_when | Expressions that define failure / change for a task |
| ignore_errors | Continue after a failed task (shown as ignored) |
| Roles / role layout | Reusable folder structure: tasks, handlers, defaults, vars, templates, files, meta |
| Meta dependencies | Roles listed in meta/main.yml that run first, once |
| Argument specs | meta/argument_specs.yml input validation |
| Ansible Vault | Built-in encryption for variables and files |
| ansible-vault encrypt / encrypt_string | Encrypt a file / one value |
| Vault ID | Label that ties encrypted content to a password source |
| SOPS | Encrypted-file editor using KMS, age or PGP (community.sops) |
| Lookup plugins | Controller-side functions that fetch data (env, hashi_vault) |
| ansible-lint | Linter with profiles (min ... production) |
| --syntax-check | Parse-only check of a playbook |
| Molecule | Test framework: create, converge, idempotence, verify, destroy |
| Assert module | Fails unless expressions hold |
| AWX | Open-source web UI/API for Ansible; upstream of AAP |
| Ansible Automation Platform | Red Hat's supported automation product (controller, hub, EEs) |
| Execution environment | Container image that acts as a control node |
| Chef / Chef Infra | Ruby-based, pull-model CM: Chef Infra Server and Client |
| Cookbook / recipe | Chef's unit of distribution / a collection of resources in Ruby |
| Pull model | Agents fetch desired state on a schedule |
| Puppet / manifest | Declarative CM / file of Puppet resources |
| Puppet agent | Daemon that sends facts and applies catalogs (runinterval 30m) |
| Puppet Bolt | Agentless task runner over SSH/WinRM |
| Salt / SaltStack | Event-driven CM and remote execution; master and minions |
| Minion / master | Salt agent / Salt server |
| State (Salt) | Desired-state declaration in an SLS file |
| Pillar / grains | Per-minion data compiled on the master / host facts |
| Reactor | Salt subsystem mapping events to actions |
| Push vs pull | Controller-initiated vs agent-initiated convergence |
| Agent vs agentless | Daemon per host vs on-demand connections |
| systemd unit | A .service or .socket file systemd manages |
| Socket activation | systemd owns the listening socket and passes it to the service |
| PHP-FPM | PHP FastCGI Process Manager running Laravel behind Nginx |
| Nginx role | The part of the Laravel role that templates and reloads the Nginx site |
| Supervisor | Process control system, Laravel's documented queue worker manager |
| Queue workers | Long-lived php artisan queue:work processes |
| php artisan | Laravel's CLI (optimize, migrate --force, queue:restart) |
| Deployer | PHP deploy tool with release directories and a Laravel recipe |
| Envoy | Laravel's Blade-syntax SSH task runner |
| Forge / Envoyer | Laravel's managed server service / zero-downtime deploy service |
| Go binary deploy | Copying a static Go binary into a release directory and restarting its unit |
References
- Ansible: Getting started — https://docs.ansible.com/ansible/latest/getting_started/index.html
- Ansible concepts — https://docs.ansible.com/ansible/latest/getting_started/basic_concepts.html
- How to build your inventory — https://docs.ansible.com/ansible/latest/inventory_guide/intro_inventory.html
- Working with dynamic inventory — https://docs.ansible.com/ansible/latest/inventory_guide/intro_dynamic_inventory.html
- Patterns: targeting hosts and groups — https://docs.ansible.com/ansible/latest/inventory_guide/intro_patterns.html
- Ansible playbooks — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_intro.html
- Using variables (precedence) — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html
- Controlling how Ansible behaves: precedence rules — https://docs.ansible.com/ansible/latest/reference_appendices/general_precedence.html
- Conditionals — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_conditionals.html
- Loops — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_loops.html
- Handlers — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_handlers.html
- Blocks — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_blocks.html
- Error handling — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_error_handling.html
- Tags — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_tags.html
- Check mode and diff mode — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_checkmode.html
- Controlling playbook execution: strategies and more — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_strategies.html
- Templating (Jinja2) — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_templating.html
- Using filters — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_filters.html
- Roles — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html
- Re-using Ansible artifacts — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse.html
- Discovering variables: facts — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html
- Lookups — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_lookups.html
- Understanding privilege escalation: become — https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_privilege_escalation.html
- Ansible Vault — https://docs.ansible.com/ansible/latest/vault_guide/vault.html
- Encrypting content with Ansible Vault — https://docs.ansible.com/ansible/latest/vault_guide/vault_encrypting_content.html
- Managing vault passwords — https://docs.ansible.com/ansible/latest/vault_guide/vault_managing_passwords.html
- Using collections in a playbook — https://docs.ansible.com/ansible/latest/collections_guide/collections_using_playbooks.html
- Ansible configuration settings — https://docs.ansible.com/ansible/latest/reference_appendices/config.html
- Releases and maintenance — https://docs.ansible.com/ansible/latest/reference_appendices/release_and_maintenance.html
- Ansible tips and tricks — https://docs.ansible.com/ansible/latest/tips_tricks/ansible_tips_tricks.html
- Windows Remote Management — https://docs.ansible.com/ansible/latest/os_guide/windows_winrm.html
- Getting started with Execution Environments — https://docs.ansible.com/ansible/latest/getting_started_ee/index.html
- ansible.builtin modules: copy, template, lineinfile, blockinfile, file, service, systemd_service, package, apt, command, shell, user, git, uri, assert, setup — https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html (and siblings under the same path)
- ansible-playbook CLI — https://docs.ansible.com/ansible/latest/cli/ansible-playbook.html
- ansible-vault CLI — https://docs.ansible.com/ansible/latest/cli/ansible-vault.html
- amazon.aws.aws_ec2 inventory — https://docs.ansible.com/ansible/latest/collections/amazon/aws/aws_ec2_inventory.html
- google.cloud.gcp_compute inventory — https://docs.ansible.com/ansible/latest/collections/google/cloud/gcp_compute_inventory.html
- community.general — https://docs.ansible.com/ansible/latest/collections/community/general/index.html
- community.sops — https://docs.ansible.com/ansible/latest/collections/community/sops/index.html
- community.hashi_vault lookup — https://docs.ansible.com/ansible/latest/collections/community/hashi_vault/hashi_vault_lookup.html
- ansible-core 2.15 changelog — https://raw.githubusercontent.com/ansible/ansible/stable-2.15/changelogs/CHANGELOG-v2.15.rst
- ansible-lint — https://docs.ansible.com/projects/lint/
- ansible-lint profiles — https://docs.ansible.com/projects/lint/profiles/
- ansible-lint configuration — https://docs.ansible.com/projects/lint/configuring/
- Molecule — https://docs.ansible.com/projects/molecule/
- Molecule configuration — https://docs.ansible.com/projects/molecule/configuration/
- AWX README — https://github.com/ansible/awx
- Galaxy: community.general — https://galaxy.ansible.com/ui/repo/published/community/general/
- Galaxy: ansible.posix — https://galaxy.ansible.com/ui/repo/published/ansible/posix/
- Chef Infra Client overview — https://docs.chef.io/client/19/overview/
- Chef cookbooks — https://docs.chef.io/client/19/cookbooks/
- Chef recipes — https://docs.chef.io/client/19/cookbooks/recipes/
- Puppet architecture — https://help.puppet.com/core/current/Content/PuppetCore/architecture.htm
- Puppet language — https://help.puppet.com/core/current/Content/PuppetCore/puppet_language.htm
- Puppet resources — https://help.puppet.com/core/current/Content/PuppetCore/lang_resources.htm
- Puppet configuration (runinterval) — https://help.puppet.com/core/current/Content/PuppetCore/Markdown/configuration.htm
- Puppet Bolt — https://help.puppet.com/bolt/current/topics/bolt.htm
- Salt Project — https://docs.saltproject.io/en/latest/topics/about_salt_project.html
- Salt states tutorial — https://docs.saltproject.io/en/latest/topics/tutorials/starting_states.html
- Salt pillar — https://docs.saltproject.io/en/latest/topics/pillar/index.html
- Salt grains — https://docs.saltproject.io/en/latest/topics/grains/index.html
- Salt reactor — https://docs.saltproject.io/en/latest/topics/reactor/index.html
- Salt event system — https://docs.saltproject.io/en/latest/topics/event/events.html
- Salt SSH — https://docs.saltproject.io/en/latest/topics/ssh/index.html
- Packer introduction — https://developer.hashicorp.com/packer/docs/intro
- HashiCorp Vault signed SSH certificates — https://developer.hashicorp.com/vault/docs/secrets/ssh/signed-ssh-certificates
- hashicorp/vault-action — https://github.com/hashicorp/vault-action
- actions/setup-python — https://github.com/actions/setup-python
- SOPS — https://github.com/getsops/sops
- Martin Fowler, ImmutableServer — https://martinfowler.com/bliki/ImmutableServer.html
- Martin Fowler, SnowflakeServer — https://martinfowler.com/bliki/SnowflakeServer.html
- Martin Fowler, ConfigurationSynchronization — https://martinfowler.com/bliki/ConfigurationSynchronization.html
- systemd.service(5) — https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html
- systemd.socket(5) — https://www.freedesktop.org/software/systemd/man/latest/systemd.socket.html
- sd_listen_fds(3) — https://www.freedesktop.org/software/systemd/man/latest/sd_listen_fds.html
- systemctl(1) — https://www.freedesktop.org/software/systemd/man/latest/systemctl.html
- coreos/go-systemd — https://github.com/coreos/go-systemd
- nginx beginner's guide — https://nginx.org/en/docs/beginners_guide.html
- PHP-FPM configuration — https://www.php.net/manual/en/install.fpm.configuration.php
- Supervisor configuration — https://supervisord.org/configuration.html
- Deployer: getting started — https://deployer.org/docs/8.x/getting-started
- Deployer Laravel recipe — https://deployer.org/docs/8.x/recipe/laravel
- Laravel 13 Envoy — https://laravel.com/docs/13.x/envoy
- Laravel 13 Deployment — https://laravel.com/docs/13.x/deployment
- Laravel 13 Queues — https://laravel.com/docs/13.x/queues
- Laravel Forge docs — https://forge.laravel.com/docs
- Envoyer — https://envoyer.io/
- Go: download and install — https://go.dev/doc/install
- Red Hat press release, 16 Oct 2015 — https://www.redhat.com/en/about/press-releases/red-hat-acquire-it-automation-and-devops-leader-ansible
- Wikipedia (secondary, dates only): Ansible — https://en.wikipedia.org/wiki/Ansible_(software); Puppet — https://en.wikipedia.org/wiki/Puppet_(software); Chef — https://en.wikipedia.org/wiki/Progress_Chef; Salt — https://en.wikipedia.org/wiki/Salt_(software); CFEngine — https://en.wikipedia.org/wiki/CFEngine