Bookmarks

Ansible

Ansible is an agentless system for automating server configuration over SSH. In this reference: inventory, playbooks, modules, variables, roles and Vault.

checked 6 Nov · next check 13 Nov · 59 min read

Sections
12
Reading
59 min
Current version
14.5.0 (ansible-core 2.21.5)
Written from
docs.ansible.com

Check status of the reference

Verified 6 Nov · next check 13 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Ansible is and how it works

Ansible is an open source automation system: you describe the desired state of your servers in playbooks, and Ansible itself brings the managed nodes to that state over SSH. No agents need to be installed on the servers.

Ansible is a good fit for configuring servers, deploying applications and managing network devices. Creating the cloud infrastructure itself — virtual machines and networks — is better left to Terraform: for the comparison, see the Terraform reference, section “What Terraform is and how it works”.

How a playbook run works

On the control node — an ordinary computer or server with Ansible installed — you maintain the inventory with the list of hosts and your playbooks. The ansible-playbook command reads the playbook, selects hosts from the inventory and runs the tasks of each play on those hosts in turn.

Normally Ansible connects to the nodes itself and runs the tasks — the push model. There is also the reverse option ansible-pull, where the nodes pull their configuration from a git repository, but it is rarely used.

bashOn the control node
# on the control nodeansible-playbook site.yml -i inventory.ini

Each task calls a module — code that Ansible copies to the managed node into a temporary directory, runs there, usually with Python, and then removes. No separate daemon is needed on the node: connections to Linux go over SSH, and to Windows over WinRM or SSH.

Push model: Ansible connects to the nodes itself; with ansible-pull, the nodes pull the configuration themselves.

What a playbook is made of

A playbook is a YAML file in which you declare the desired state, not a sequence of commands. It consists of plays — large blocks, each tied to a host group and containing an ordered list of tasks:

yamlsite.yml — an example playbook
- name: Set up web servers  hosts: webservers   tasks:    - name: Ensure nginx is installed      ansible.builtin.apt:        name: nginx        state: present     - name: Ensure nginx is running      ansible.builtin.service:        name: nginx        state: started
  • Control node — the machine that ansible-playbook, ansible and the other tools run from; Ansible is not installed on the managed nodes.
  • Managed nodes — servers, network devices and other machines that Ansible manages.
  • Inventory — a list of managed nodes grouped together, for example webservers.
  • Task — a single module call with specific arguments.
  • Module — the code behind an action: install a package, copy a file, restart a service.
  • Collection — the distribution format for playbooks, roles, modules and plugins; modules are grouped into collections.

Module names in playbooks are written in full: ansible.builtin.apt is the fully qualified name (FQCN) of the apt module from the built-in collection. Fully qualified names avoid ambiguity when the same module exists in different collections.

Idempotency and reporting

Most modules are idempotent: if the system is already in the desired state, the module changes nothing. So the playbook can be run again — the result will not change.

After the run, Ansible prints the recap (PLAY RECAP): how many tasks on each host finished as ok, changed or failed. The changed=0 line in the second run confirms that the playbook changes nothing when run again.

textExample output
web1 : ok=3  changed=2  failed=0web2 : ok=3  changed=2  failed=0

What you need to know first

  • SSH and Linux basics — files, permissions, processes; the Linux reference.
  • YAML syntax — playbooks are written in it; for details see the section “Playbooks: plays, tasks and handlers”.
  • Python on the managed nodes — the modules run through it; for Windows nodes, PowerShell.

Section sources

the section is written from these pages

Cheat sheet

The cheat sheet is a single page of common Ansible commands: inventory, ad-hoc commands, playbooks, Vault, collections and roles, and debugging. Replace the names in the examples (hosts.ini, web, site.yml) with your own. The flags are covered in detail in the sections on playbooks and variables.

Inventory

TaskCommand
View groups and hostsansible-inventory -i hosts.ini --graph
Groups with variablesansible-inventory -i hosts.ini --graph --vars
The whole inventory as JSONansible-inventory -i hosts.ini --list
A host or a groupansible web -i hosts.ini -m ping
A host without an inventoryansible 192.0.2.10, -m ping -u admin

Ad-hoc commands

TaskCommand
Check that hosts are reachableansible all -i hosts.ini -m ping
A package on Debian-based hostsansible web -i hosts.ini -b -m apt -a "name=apache2 state=present"
A package on RHEL-based hostsansible web -i hosts.ini -b -m dnf -a "name=httpd state=present"
A file with permissions and an owneransible web -i hosts.ini -b -m copy -a "src=app.conf dest=/etc/app.conf owner=root mode=0644"
Restarting a serviceansible web -i hosts.ini -b -m service -a "name=nginx state=restarted"
A shell command on the hostsansible web -i hosts.ini -b -a "uptime"

In ansible web -i hosts.ini -m ping, the word web is a group or a host from the inventory. Substitute a group name, the pattern web* or all for it. The -b flag escalates privileges through become, with sudo as the default.

Playbooks

TaskCommand
Run a playbookansible-playbook -i hosts.ini site.yml
Check the syntaxansible-playbook -i hosts.ini site.yml --syntax-check
Dry runansible-playbook -i hosts.ini site.yml --check --diff
One host groupansible-playbook -i hosts.ini site.yml --limit web
Tasks with a tagansible-playbook -i hosts.ini site.yml --tags config
Except tasks with a tagansible-playbook -i hosts.ini site.yml --skip-tags config
A variable from the command lineansible-playbook -i hosts.ini site.yml -e "env=prod"
A list of tasks without running themansible-playbook -i hosts.ini site.yml --list-tasks
A list of tagsansible-playbook -i hosts.ini site.yml --list-tags
With privilege escalationansible-playbook -i hosts.ini site.yml -b -K

--check --diff shows what would change and changes nothing: templates and files show a diff, while for services and packages there is no guarantee, because modules check the state in different ways.

Vault

TaskCommand
Create an encrypted fileansible-vault create secrets.yml
Edit itansible-vault edit secrets.yml
Read it in the terminalansible-vault view secrets.yml
Encrypt an existing fileansible-vault encrypt vars.yml
A variable on one lineansible-vault encrypt_string --name db_pass 'db-pass'
Decrypt into a fileansible-vault decrypt secrets.yml --output secrets.txt
The password from a file, not from the terminalansible-playbook --vault-password-file ~/.vault_pass site.yml

Collections and roles

TaskCommand
Install a collectionansible-galaxy collection install community.general
A list of collections from a fileansible-galaxy collection install -r requirements.yml
Installed collectionsansible-galaxy collection list
Install a roleansible-galaxy role install example.role
Installed rolesansible-galaxy role list
A skeleton for your own roleansible-galaxy role init my_role

Debugging and reference

TaskCommand
Module documentationansible-doc ansible.builtin.copy
A snippet for a playbookansible-doc -s ansible.builtin.copy
A list of modulesansible-doc -t module -l
What is overridden in the configurationansible-config dump --only-changed
Versions and pathsansible --version
Verbose output of a runansible-playbook -i hosts.ini site.yml -vvv
Diagnosing the connectionansible web -i hosts.ini -m ping -vvvv

The -vvv level shows task details, -vvvv adds the SSH log as well. Verbose output writes secrets too, so on production hosts it is enabled selectively, for a single command.

Section sources

the section is written from these pages

Installation and first run

Ansible is installed on a single machine, the control node, which manages the other machines — the managed nodes — over SSH, with no agents installed on them. The package is installed with pipx or pip, and ansible --version verifies the installation.

There are two packages. ansible-core is the minimal one: the playbook language, the executor and the built-in modules. ansible is the full one: the same ansible-core plus community collections with modules for clouds, networks and services. To start with, install the full ansible: missing collections can be added later, and extra ones do no harm.

Node requirements

Almost any UNIX-like system with Python 3 can serve as the control node: Red Hat, Debian, Ubuntu, macOS, BSD; Windows works only under WSL — without it, not at all. A managed node does not need Ansible installed: an account with SSH access and a POSIX shell is enough, plus Python 3, for which Ansible prepares the module code at run time. Windows nodes are usually managed not over SSH but through WinRM or PowerShell remoting (SSH is also possible); network modules are the exception — they need no Python on the device.

Installation with pipx

pipx is the approach the documentation recommends: it installs a tool into its own environment without touching the system Python. This solves the problem found on recent distributions, where installing packages into the system Python with pip is forbidden.

bashon the control node
# full package: core plus community collectionspipx install --include-deps ansible# or the minimal package without collectionspipx install ansible-core
bash
# upgrade to a new releasepipx upgrade --include-injected ansible

Installation with pip in a venv

When Ansible is needed within a specific project, install it into a venv virtual environment — the project’s dependencies will not clash with the system ones. To upgrade, run the same command with the --upgrade flag. Installing into the user directory with pip install --user also works, but on distributions with a protected system Python this path is closed.

bashon the control node
python3 -m venv .venvsource .venv/bin/activate# in the activated environmentpython3 -m pip install ansible

Package from the distribution repository

Fedora and Arch ship Ansible in their standard repositories. For CentOS Stream, AlmaLinux and Rocky the package lives in the EPEL repository: enable it and install with the same dnf commands. On Ubuntu, recent versions are distributed through the PPA ppa:ansible/ansible:

bashUbuntu
sudo apt updatesudo apt install software-properties-common# repository with recent releasessudo add-apt-repository --yes --update ppa:ansible/ansiblesudo apt install ansible

Checking the installation

bashon the control node
ansible --version
textexample output
ansible [core ...]  config file = None  configured module search path = ...  ansible python module location = ...  executable location = ...  python version = 3.13.7 ...

The command prints a block with the version. The number shown is the ansible-core version, because it is ansible-core that runs. The full package has a separate command, ansible-community --version.

First run: pinging hosts

Ansible takes hosts from an inventory — a file listing machines and groups. For a test, two lines are enough:

iniinventory.ini
[servers]web1 ansible_host=203.0.113.10web2 ansible_host=203.0.113.11
bashon the control node
# connection runs as your useransible servers -i inventory.ini -m ping
textexample output
web1 | SUCCESS => {    "ansible_facts": {        "discovered_interpreter_python": ...    },    "changed": false,    "ping": "pong"}

The lines SUCCESS and "ping": "pong" mean that the SSH connection succeeded, Python on the node was found and the module ran. On first contact SSH will ask you to confirm the node’s fingerprint — answer yes. Inventory and host groups are covered in the section “Inventory and host templates”; modules and ad-hoc commands are covered in the section “Modules and ad-hoc commands”.

The ansible.cfg file

There is no need to type the -i flag and the user name every time: Ansible reads settings from the ansible.cfg file. The search proceeds in order through four locations: the ANSIBLE_CONFIG environment variable, ansible.cfg in the current directory, ~/.ansible.cfg in the home directory, /etc/ansible/ansible.cfg. The first file found is used and the rest are ignored.

iniansible.cfg
[defaults]inventory = ./inventory.iniremote_user = deploy

inventory replaces the -i flag, remote_user sets the user for logging in to the managed nodes; without it, Ansible connects as the current user. To make sense of all the settings, use the command ansible-config init --disabled > ansible.cfg: it generates a template with all the parameters and comments on them.

Section sources

the section is written from these pages

Inventory and host patterns

An inventory is the list of managed nodes from which Ansible takes hosts and groups to run playbooks and ad-hoc commands. Hosts are described in a YAML or INI file, and variables in the file itself or alongside it, in group_vars/ and host_vars/; selection patterns (webservers:&production) determine exactly which nodes a run will target.

The simplest inventory is a single file listing hosts and groups; the path to it is passed with the -i flag, and the default file is /etc/ansible/hosts. When there are many hosts, the inventory is assembled from a directory with several files: one per team or project, and static and dynamic sources can be mixed.

Formats: YAML and INI

Out of the box, Ansible understands two inventory formats — YAML and INI; other formats and sources are provided by plugins. YAML is the main one: playbooks are written in it, and it does not confuse value types. The INI format is shorter and remains common. Both describe the same things: groups, hosts within groups, nested groups and variables.

yamlinventory.yaml
webservers:  hosts:    web1.example.com:    web2.example.com:dbservers:  hosts:    db1.example.com:    db2.example.com:production:  children:    webservers:    dbservers:  vars:    ntp_server: ntp.example.com
inithe same inventory in INI
[webservers]web1.example.comweb2.example.com [dbservers]db[1:2].example.com [production:children]webserversdbservers [production:vars]ntp_server=ntp.example.com

Nested groups are written as children in YAML and as :children in INI: a host of a child group automatically becomes a member of the parent too. A group may have several parents and children, but cycles are not allowed. A host can belong to several groups — Ansible will merge their data. Group names follow the rules for variable names; redefining a group or a host does not create a second entity but adds to or overwrites its data.

Two groups always exist, even without your involvement: all contains every host in the inventory, and ungrouped — the ones that did not end up in any other group. For similar hosts, lists are shortened with ranges: db[1:2].example.com defines db1 and db2, and the step is given as a third number — www[01:50:2].example.com.

Host and group variables

Host-specific variables — connection parameters — are written directly in the inventory. Values in the :vars section of the INI format always become strings, so it is better to cast a type with a filter in a task than to rely on the inventory.

yamlconnection parameters
webservers:  hosts:    web1.example.com:      ansible_host: 192.0.2.10      ansible_user: deploy      ansible_port: 2222      ansible_python_interpreter: /usr/bin/python3
ParameterWhat it sets
ansible_hostthe address to connect to, if it differs from the host name
ansible_userthe user Ansible logs into the host as
ansible_portthe port to connect on, if not the standard 22
ansible_python_interpreterthe path to Python on the host, if automatic interpreter detection is not suitable

Growing variables are moved out of the inventory into the group_vars/ and host_vars/ directories — next to the inventory or the playbook. A file is named after a group or a host and contains ordinary YAML, including lists and dictionaries that an inventory cannot hold.

textinventory directory layout
production/  hosts.yaml  group_vars/    webservers.yaml  host_vars/    web1.example.com.yaml

How values from different places override one another is covered in the section “Variables and facts”.

Host selection patterns

A pattern is the value of hosts: in a playbook and a positional argument of an ad-hoc command. It works only with what the inventory contains: a host that is absent from it cannot be selected, either by name or by address.

PatternWhat a run targets
allevery host in the inventory
webserversa group or a single host with that name
webservers:dbserversunion: both groups
webservers:!staginga group without the hosts of another group
webservers:&productionintersection: only those belonging to both
web*.example.coma wildcard over host names
~(web|db)\.example\.coma regular expression after ~

Operations are applied in the order : (union), then &, then !, so webservers:dbservers:&staging:!phoenix means: hosts of the webservers and dbservers groups that also belong to staging but not to phoenix. A comma can be written instead of the colon — it is more convenient in ranges and IPv6 addresses.

bashnarrowing the selection with the --limit flag
# one host by nameansible-playbook -i inventory site.yml --limit web1.example.com # all hosts except staging; quotes are requiredansible-playbook -i inventory site.yml --limit 'all:!staging' # by wildcardansible-playbook -i inventory site.yml --limit 'web*'

In a playbook, the selection is set the same way:

yamlsite.yml
- name: Nginx on the web servers  hosts: webservers  tasks:    - name: Restart nginx      ansible.builtin.service:        name: nginx        state: restarted      become: true

Dynamic inventory

When hosts appear and disappear — cloud machines, containers — a static file quickly goes out of date. Such an inventory is connected with plugins: a plugin asks an external source — a cloud provider, an LDAP directory, a configuration management system — for the list according to its configuration and hands it to Ansible. Plugins are the recommended way; older scripts are supported through the script plugin. A dynamic source is specified with the same -i, and several sources — even a static and a dynamic one — can be mixed in a single directory or listed with the -i flag several times.

Checking the inventory

Before running a playbook, look at how Ansible understood the inventory: --graph draws the tree of groups, and with the --vars flag — the variables too (it works only with --graph); --list prints JSON with all hosts.

bashon the control node
ansible-inventory -i inventory --graph --varsansible-inventory -i inventory --list

Playbooks, tasks and handlers are covered in the section “Playbooks: plays, tasks and handlers”; the rules of variable precedence — in the section “Variables and facts”.

Section sources

the section is written from these pages

Playbooks: plays, tasks and handlers

A playbook is a YAML file where you describe the desired state of your servers. A play inside it declares which tasks run on which hosts. Ansible takes each task across all the hosts. Running it again changes nothing.

A play declares what it acts on and what it does: hosts — a group from the inventory, become — permission to work as root, vars — variables of the play. Inside is a list of tasks, and after them — handlers, which fire on changes.

yamlsite.yml — the reference playbook
- name: Set up nginx  hosts: web  become: true   tasks:    - name: Install nginx      ansible.builtin.apt:        name: nginx        state: present     - name: Copy nginx.conf      ansible.builtin.template:        src: nginx.conf.j2        dest: /etc/nginx/nginx.conf      notify: Restart nginx     - name: Enable and start nginx      ansible.builtin.service:        name: nginx        state: started        enabled: true   handlers:    - name: Restart nginx      ansible.builtin.service:        name: nginx        state: restarted

Order of execution

Ansible works through the playbook from top to bottom: first the first play in full, then the second. Within a play the tasks run in turn, and each one gets around all the hosts of its pattern before the next one starts. As many processes touch hosts at once as forks specifies (5 by default); the flag -f or ansible.cfg changes the value.

If a task fails on a host, that host drops out of the play — the rest carry on. Hosts that dropped out because of an error also skip the handlers: the config may stay updated, but without a restart of the service. The flag --force-handlers runs the notified handlers even on such hosts.

The serial key limits the batch of hosts for a play: serial: 1 rolls changes out one host at a time, serial: "30%" — 30% per pass. This is what a typical rolling update looks like: while the second batch is being updated, the first is already serving users.

The notification accumulates over the whole play: three tasks with notify — one restart.

Handlers and notify

A handler is a task from the handlers section that runs not in order but on a notification. A task with the notify key lists handler names; they fire only if the task reported the changed status: the copy of the config did not change — the service is not restarted.

Handler names are unique within a play; the order they run in is set by their order in handlers, not in notify. Any number of tasks may notify the same name — the handler still runs only once. The listen key groups handlers into a theme: notify: restart web services runs them all at once.

By default handlers wait for the end of the play. If a restart is needed earlier — for example, so that later tasks work with the service already up — put an ansible.builtin.meta: flush_handlers task where it is needed. The notified handlers then run straight away, not at the end.

yaml
- name: Restart now, before the next tasks  ansible.builtin.meta: flush_handlers

Conditions, loops and task results

The when key skips a task on hosts where the condition is false. It is a Jinja2 expression without double curly braces; in a list the conditions are joined with “and”:

yaml
- name: Configure SELinux for nginx  ansible.posix.seboolean:    name: httpd_can_network_connect    state: true    persistent: true  when: ansible_facts['os_family'] == "RedHat"

The loop key runs a task once for each item of a list; the current item is the item variable. The register key stores a task’s result in a variable: the status, the command output. From the result you read rc (the return code), stdout, changed; the stdout_lines list is ready for the next loop.

yaml
- name: List home directories  ansible.builtin.command: ls /home  register: home_dirs - name: Create a backup folder per user  ansible.builtin.file:    path: /mnt/backup/{{ item }}    state: directory    mode: "0750"  loop: "{{ home_dirs.stdout_lines }}"

What counts as a failure and a change

The failed_when and changed_when keys redefine when a task reports a failure or a change. These are Jinja2 expressions too, usually on a registered result. Several conditions in a list are joined with “and”; for “or” write a single expression with or:

yaml
- name: Import a database dump  ansible.builtin.command: psql -f /tmp/dump.sql  register: import_result  # failed, unless the dump is already applied  failed_when: >-    import_result.rc != 0    and 'already exists' not in import_result.stderr

The block key groups tasks into a block with shared keys and its own error handling: rescue runs when the block fails, always — whatever the outcome:

yamlblock: rescue and always
- name: Deploy with a rollback  block:    - name: Stop the app      ansible.builtin.service:        name: myapp        state: stopped    - name: Copy the new release      ansible.builtin.copy:        src: releases/2026-11-06/        dest: /srv/myapp/  rescue:    - name: Start the previous release      ansible.builtin.service:        name: myapp        state: started  always:    - name: Report the deploy result      ansible.builtin.debug:        msg: deploy finished

Tags, check mode and diff

The tags key marks tasks so that part of a playbook can be run: --tags config runs only the marked tasks, --skip-tags config — everything except the marked ones. --list-tags shows the list of tags, --list-tasks the list of tasks. The tags always and never are reserved: the first runs a task no matter which tags are selected, the second — never.

A trial run with --check changes nothing: the modules that support it report what they would have done. Together with --diff it also shows the difference in files between “before and after”:

bashon the control node
ansible-playbook site.yml --check --diff# only one group and the tasks with the config tagansible-playbook site.yml --limit web --tags config

The reference playbook installs nginx and restarts it only when the config changes. Modules, Jinja2 templates and ad-hoc commands — in the section “Modules and ad-hoc commands”, variables — in the section “Variables and facts”, roles — in the section “Roles and collections”.

Section sources

the section is written from these pages

Modules and ad-hoc commands

A module is a unit of work in Ansible: install a package, copy a file, restart a service, create a user. A single ad-hoc command runs a module across a group of hosts at once, without a playbook — one-off tasks are handled this way, while repeatable work is described as tasks in a playbook.

Fully qualified module names

Every module has a fully qualified name — the FQCN (Fully Qualified Collection Name): collection, dot, name. Built-in modules live in ansible.builtin, community modules in their own collections: community.postgresql, community.general. The short name apt works too, but the fully qualified name is safer: modules with the same name exist in different collections, and the fully qualified name always points to the right one. How to install collections is covered in the section “Roles and collections”.

bashon the control node
# short name — works, but depends on collection orderansible web -b -m apt \  -a "name=nginx state=present" # fully qualified name — always the same moduleansible web -b -m ansible.builtin.apt \  -a "name=nginx state=present"

Which module to choose

A ready-made module covers a typical task, so there is no need to write commands by hand: the module checks the state itself and does only what is missing.

TaskModule
Packages on Debian and Ubuntuansible.builtin.apt
Packages on Fedora, RHEL, CentOSansible.builtin.dnf
Packages on any systemansible.builtin.package
Copy a file or textansible.builtin.copy
Permissions, owner, directory, linkansible.builtin.file
One line in a config fileansible.builtin.lineinfile
File from a Jinja2 templateansible.builtin.template
Service on any init systemansible.builtin.service
Systemd unit: service, timeransible.builtin.systemd_service
Usersansible.builtin.user
Command without a shellansible.builtin.command
Command with pipes and substitutionansible.builtin.shell

The package and service modules are dispatchers: they pick the module for the system they found while gathering facts — apt on Debian, dnf on Red Hat. Such a call works across heterogeneous hosts, but only takes common arguments — options specific to apt cannot be passed through package.

Module arguments

Almost all modules take arguments as key=value separated by spaces — in an ad-hoc command they are passed with the -a flag. Complex values are passed as a JSON string: -a '{"name": "nginx"}'. In a playbook the same arguments are written as a YAML dictionary, as in the apt example below.

yamla playbook task
- name: Install nginx  ansible.builtin.apt:    name: nginx    state: present    update_cache: true

state: present means “the package must be installed, leave the version alone”, latest — “upgrade to the newest one”, absent — “remove it”. Other modules have a different set of state values: for file they are directory, link, touch, absent, for service — started, stopped, restarted, reloaded.

Why command and shell are the last resort

Most modules are idempotent: run again on a node that is already set up, and they change nothing. command and shell work differently — they run the command on every execution, so a playbook that uses them cannot be re-run safely. Turn to them when no ready-made module exists — for a one-off script with unusual logic, for example.

The difference within the pair: command runs the program without a shell — pipes, redirections and $VAR do not work there, but accidental substitution in the arguments is ruled out. shell runs the command through /bin/sh and can do all of that, but demands careful quoting. Both have a safety net: creates=/path/to/file skips the command if the file already exists, removes — the other way round, runs it only when the file is present.

yamlplaybook
- name: Download the installer once  ansible.builtin.command:    cmd: curl -o /tmp/app.deb https://example.com/app.deb    creates: /tmp/app.deb

The ad-hoc command

An ad-hoc command is a one-off invocation of a module with the ansible utility: it is not saved to a file and does not suit repeatable configuration, but it runs in seconds. The command takes its host pattern from the inventory (more detail in the section “Inventory and host templates”), the -m flag sets the module, -a — the arguments.

bashon the control node
# install nginx on the web group as rootansible web -b -m ansible.builtin.apt \  -a "name=nginx state=present" # restart nginx on the web serversansible webservers -b \  -m ansible.builtin.service \  -a "name=nginx state=restarted" # what would change, change nothingansible all -C \  -m ansible.builtin.copy \  -a "content=debug=true dest=/etc/app.conf" # gather the facts of one hostansible db1 -m ansible.builtin.setup \  -a "filter=ansible_*_ipv4"
FlagWhat it doesDefault
-mWhich module to runansible.builtin.command
-aModule arguments as key=value or JSON—
-bPrivilege escalation (become), usually sudoOff
-KAsk for the password for -b—
-fHow many hosts to process in parallel5
-uSSH login userCurrent user
-CCheck mode: changes nothingOff

By default ansible falls back to the command module when no module is given: ansible atlanta -a "/sbin/reboot". For everything else, write -m.

Module reference

ansible-doc shows the reference for any module, with examples — it works from the command line and needs no internet. The -l flag prints the full list of installed modules; it is long, so it is easier to filter it.

bashon the control node
# module reference, with examplesansible-doc ansible.builtin.apt # list of all installed modulesansible-doc -l

There are about seventy built-in modules; the rest live in community collections. Network devices are managed through collections too: community.routeros for MikroTik RouterOS (more detail in the MikroTik reference), cisco.ios for Cisco.

Section sources

the section is written from these pages

Variables and facts

A variable is a named value that makes one playbook work for different hosts: a port, a path, a package version. Ansible gathers the data about the host itself — the OS, addresses, disks — and calls it facts. If one name is set in several places, the variable from the more specific place wins.

Where to set variables

The same value can be declared in the inventory, in a playbook, in a separate file or passed at run time — Ansible will pick them all up. Choose the place by the lifetime of the value: something shared by a group goes into the inventory, something for a single run goes on the command line.

PlaceWhat to put there
Inventory: group_vars, host_varspersistent values of a group or a host
vars in a playvalues of this run: package names, flags
vars_filesa separate YAML file attached to a play
a role’s defaults and varsrole settings: defaults are easy to override
the -e flaga one-off pass: a release, a value from Vault
yamlplaybook
- hosts: webservers  vars:    app_port: 8080  vars_files:    - vars/common.yml   tasks:    - name: Show a variable      ansible.builtin.debug:        msg: "listening on {{ app_port }}" 
yamlgroup_vars/webservers.yml
# next to the inventory, for the group webserversapp_port: 8080app_user: webapp
bashoverride at run time
ansible-playbook site.yml -e "app_port=9090"

Values passed with -e can be written as a key=value string, a JSON string or a file: ansible-playbook site.yml -e @extra.yml.

Which variable wins

If one name is set in several places, Ansible applies variable precedence: in the documentation this is a list of more than twenty levels. In practice a simplified ladder and one rule are enough: the more specific the place, the higher the priority.

The arrows lead from a weaker variable to the one that overrides it.

Exceptions: explicit includes — vars_files, include_vars and a role’s vars — override the inventory, not the other way round. And if you are not sure which value will be picked up, pass it with -e: extra vars beat any other variables.

Facts: host data

Before each play the setup module queries the host and stores the result in ansible_facts: the OS, IP addresses, disks, memory. A fact is addressed like a dictionary entry: ansible_facts['os_family']. By default the same values are also duplicated under flat names such as ansible_os_family.

yamlplaybook
- name: Print all facts  ansible.builtin.debug:    var: ansible_facts - name: Debian gets the apt module  ansible.builtin.apt:    name: nginx  when: ansible_facts['os_family'] == "Debian" 
bashone host’s facts in the terminal
ansible db1 -m ansible.builtin.setup -a "filter=ansible_default_ipv4"

Fact gathering is on by default and costs one SSH session per host. If the playbook does not need facts, switch them off with the line gather_facts: false — on thousands of hosts this noticeably speeds up the run.

By default the cache is off: facts live in memory until the end of the run. A fact caching plugin keeps them between runs, so facts of one host can be used while configuring another. fact_caching_timeout limits how long the entries live; the example shows the default value, 86400 (a day).

iniansible.cfg
[defaults]fact_caching = jsonfilefact_caching_connection = .ansible_cachefact_caching_timeout = 86400

Magic variables

Besides facts there are magic variables — about Ansible itself and the inventory. They cannot be set manually: their names are reserved.

VariableWhat it holds
inventory_hostnamethe current host’s name from the inventory
hostvarsa dictionary of the variables and facts of any host
groupsa dictionary “host group → list of hosts”
group_namesthe groups of the current host
yamlplaybook
- name: Address of another host for a template  ansible.builtin.debug:    msg: "{{ hostvars['app1']['ansible_facts']['default_ipv4']['address'] }}" - name: Every host of a group  ansible.builtin.debug:    msg: "{{ groups['webservers'] }}" 

The facts of another host are available through hostvars only after they have been gathered or taken from the cache. Variables declared at the play level are not tied to individual hosts and do not get into hostvars.

register and set_fact

Both keywords create variables during a run. register saves the result of a task: the return code, the output, the changed files. set_fact assigns a value by computing it.

yamlplaybook
- name: Check the config before reload  ansible.builtin.command: nginx -t  register: nginx_test  ignore_errors: true - name: Reload only when the config is valid  ansible.builtin.systemd:    name: nginx    state: reloaded  when: nginx_test.rc == 0 - name: A short name for templating  ansible.builtin.set_fact:    short: "{{ inventory_hostname.split('.')[0] }}" 

A variable from register is tied to the host on which the task ran and lives until the end of the playbook run, including later plays; other hosts see it through hostvars too. The value of set_fact is also tied to a host; to make it outlive the run, set cacheable: true — then it goes into the fact cache.

Variables substituted into Jinja2 templates and filters for transforming values are covered in the Ansible reference, the section “Jinja2 templates and filters”.

Section sources

the section is written from these pages

Jinja2 templates and filters

A template is a text file with Jinja2 tags: variables {{ }}, conditionals {% if %}, loops {% for %}. Ansible renders the template on the control node, and the template module copies the finished result to the host: a single nginx.conf.j2 file gives every server its own configuration.

Templates are stored in a templates directory next to the playbook or in the role’s templates/; the .j2 extension is a convention that makes them easy to spot. In the task you specify src — the path to the template on the control node — and dest — the path on the host; plus mode, owner and group. The template and its data must be utf-8.

validate checks the new file before the old one is replaced; notify wakes the handler.

A worked example: nginx.conf.j2

jinjanginx.conf.j2 — the template
# {{ ansible_managed }}user {{ nginx_user | default('www-data') }};worker_processes auto; events {    worker_connections 1024;} http {    include /etc/nginx/mime.types;     server {        listen {{ nginx_port }}{% if tls_enabled %} ssl{% endif %};        server_name {{ inventory_hostname }};         {% for site in sites %}        location {{ site.path }} {            proxy_pass {{ site.url }};        }        {% endfor %}         {% if tls_enabled %}        ssl_certificate {{ tls_cert }};        ssl_certificate_key {{ tls_cert_key }};        {% endif %}    }}
yamlgroup_vars/webservers.yml
nginx_port: 443tls_enabled: truenginx_user: www-datatls_cert: /etc/letsencrypt/live/example.com/fullchain.pemtls_cert_key: /etc/letsencrypt/live/example.com/privkey.pemsites:  - path: /app    url: http://127.0.0.1:8000  - path: /static/    url: http://127.0.0.1:8001

The values are ordinary variables from group_vars or the role; the inventory_hostname fact is different for every host, so server_name is different too. You can render more than files: any task value — for example dest: "{{ item.path }}" — is evaluated the same way.

yamlthe playbook
- hosts: webservers  tasks:    - name: Render nginx config      ansible.builtin.template:        src: nginx.conf.j2        dest: /etc/nginx/nginx.conf        mode: '0644'        validate: nginx -t -c %s        backup: true      notify: Restart nginx   handlers:    - name: Restart nginx      ansible.builtin.service:        name: nginx        state: restarted

Rendering happens on the control node: only the finished file travels over the network. The validate key receives the path to the new file via %s and runs before the old file is replaced — if the check fails, nothing is replaced. backup: true keeps the previous file alongside, with a timestamp. A task with notify wakes the handler, and it restarts the service once after all tasks if the file changed.

Filters

A filter transforms a value after a pipe: {{ nginx_port | default(80) }}. Filters run on the control node together with the template and stack into chains: {{ ports | default([]) | join(', ') }}.

FilterWhat it does
default(8080)substitutes a value if the variable is not defined; with a second argument of true — also when it is empty or false
join(', ')joins a list into a string with a separator
to_nice_yaml(indent=2)turns a structure into readable YAML; there is also to_nice_json
regex_replace('^a.*i(.*)$', 'a\\1')replacement by regular expression
password_hash('sha512')hashes a password, for example for /etc/shadow; without a salt — a random one
mandatoryan error if the variable is missing — for cases where undefined values are allowed

A different template per OS family

The template name is built from the ansible_os_family fact: every family of hosts gets its own file.

yamlthe playbook
- name: Deploy OS-specific nginx config  ansible.builtin.template:    src: "nginx.conf.{{ ansible_os_family }}.j2"    dest: /etc/nginx/nginx.conf    mode: '0644'

When a parameter is optional

default(omit) removes the parameter from the module call entirely: for files without mode, the host’s umask sets the permissions.

yamlthe playbook
- name: Touch files with optional mode  ansible.builtin.file:    dest: "{{ item.path }}"    state: touch    mode: "{{ item.mode | default(omit) }}"  loop:    - path: /tmp/foo    - path: /tmp/bar      mode: '0444'

A stable password hash

A salt derived from inventory_hostname makes the hash the same from one run to the next. Keep the password itself in Vault — see the section “Security: Vault and become”.

yamlthe playbook
vars:  pw_salt: "{{ 65534 | random(seed=inventory_hostname) | string }}" tasks:  - name: Create admin user    ansible.builtin.user:      name: admin      password: "{{ admin_pass | password_hash('sha512', pw_salt) }}"

Section sources

the section is written from these pages

Roles and collections

A role is a reusable package for Ansible: tasks, handlers, templates and variables laid out in standard directories. A collection is a distribution format for such content: a single package can hold roles, modules and plugins. Structure your own code as roles, and bring in other people’s from Ansible Galaxy.

When a playbook grows, break it into roles: each one takes care of its own service — nginx, PostgreSQL, backups — and is included with a single line. Ansible looks for roles in collections, in the roles/ directory next to the playbook and in the paths from roles_path — by default ~/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles.

Role structure

There are seven standard directories; none of them is mandatory — you can skip the ones you don’t use. In each directory, Ansible reads the main.yml file on its own, without it being mentioned in tasks:

textwebtier role structure
webtier/├── tasks/│   └── main.yml      # tasks├── handlers/│   └── main.yml      # handlers├── templates/        # Jinja2 templates (*.j2)│   └── nginx.conf.j2├── files/            # files for copy and script│   └── foo.sh├── vars/│   └── main.yml      # variables with high precedence├── defaults/│   └── main.yml      # default values└── meta/    └── main.yml      # metadata and dependencies

The difference between vars/ and defaults/ is precedence: a variable from defaults/ is overridden by almost any other source, so defaults go there, and vars/ holds what the role must not change. Paths to files inside a role are shortened: tasks see their own role’s files/, templates/ and tasks/ without full paths. Other YAML files in these directories are not picked up on their own — include them separately, for example tasks for a specific platform.

Including a role: roles, include_role, import_role

There are three ways to include a role: the roles: key at the play level, and include_role and import_role among the tasks. With roles:, Ansible processes the role in advance, while parsing the playbook: first pre_tasks, then roles, then the play’s tasks and finally post_tasks.

yamlplaybook
- hosts: web  roles:    - common    - role: webtier      vars:        app_port: 8080

include_role is dynamic inclusion: the role enters the task flow where it occurs and may sit in a loop. import_role is static: the role is expanded while the playbook is parsed and works like roles:. Both can include more than main.yml:

yamlplaybook
- name: Deploy web app  ansible.builtin.include_role:    name: webtier    tasks_from: deploy.yml  loop: "{{ sites }}" - name: Run nginx tasks statically  ansible.builtin.import_role:    name: webtier    tasks_from: nginx.yml
Featureinclude_roleimport_role
When it is processedat runtimewhen the playbook is parsed
loop cyclesthe role runs for each itemnot possible
when on the includeapplies to the include itself only, leaves the role’s tasks untouchedinherited by all of the role’s tasks
Tags: --list-tagsthe role’s tags are missing from the listall tags are visible
--list-tasksthe role’s tasks are not listedall tasks are listed

include_tasks and import_tasks

For task files there is the same pair: include_tasks includes a file at runtime, import_tasks when the playbook is parsed. An included file can rely on the results of earlier tasks, an imported one cannot: by the time the playbook is parsed they don’t exist yet. Variables for the import must be known in advance: set them via vars or --extra-vars.

yamltasks/main.yml of the role
- name: Install a web server  ansible.builtin.import_tasks: redhat.yml  when: ansible_facts['os_family']|lower == 'redhat' - name: Install a web server  ansible.builtin.import_tasks: debian.yml  when: ansible_facts['os_family']|lower == 'debian'

Handlers in an included file behave differently from those in an imported one: an included file is notified by the name of the include task itself — all of its tasks then run as handlers; with an imported file, individual tasks are notified. The documentation, too, advises against mixing includes and imports in one playbook.

Your roles and other people’s roles: ansible-galaxy

ansible-galaxy role init scaffolds a new role with the standard directories and main.yml files. The same command also installs and lists what is installed:

bashon the control node
ansible-galaxy role init webtieransible-galaxy role listansible-galaxy role install geerlingguy.apache,4.2.1

Other people’s roles are installed with the ansible-galaxy role install command into the first writable path from the same list as used when searching. The list of roles is written to requirements.yml: that way a project installs everything it needs with a single command.

yamlrequirements.yml
---# requirements.ymlroles:  # version ranges are not supported for roles  - name: geerlingguy.apache    version: "4.2.1"  - name: geerlingguy.postgresqlcollections:  - name: community.general    version: ">=7.0.0"  - name: community.docker
bashon the control node
ansible-galaxy install -r requirements.yml

A role from Galaxy is specified as namespace.role_name; pin the version after a comma, and a Git repository can be given as well. Version ranges are not supported for roles. ansible-galaxy install -r installs both roles and collections from one file, and ansible-galaxy collection install -r — collections only; a role is removed by ansible-galaxy role remove namespace.role_name.

Collections: namespace, installation and FQCN

A collection is a package with roles, modules and plugins inside a namespace: the name community.postgresql means the namespace community and the collection postgresql. Collections are installed with the ansible-galaxy collection install command; by default — from Ansible Galaxy into ~/.ansible/collections/ansible_collections.

bashon the control node
ansible-galaxy collection install community.dockeransible-galaxy collection install community.postgresql:==5.0.0ansible-galaxy collection install community.docker --upgradeansible-galaxy collection list

Each collection has one version installed at a time; --upgrade moves you to the latest one. For a project, keep collections next to the playbooks in collections/ansible_collections/ — then environments don’t interfere with each other.

In tasks, refer to content by its full name — the FQCN (fully qualified collection name, see the section “Modules and ad hoc commands”): community.docker.docker_container belongs to that exact collection, and the full name always points to the right content, even if the same short name exists in another collection.

yamlplaybook
- name: Reference a collection content using FQCN  hosts: web  tasks:    - name: Run a container      community.docker.docker_container:        name: demo        image: nginx:1.30        state: started     - name: Import a role from a collection      ansible.builtin.import_role:        name: community.zabbix.zabbix_agent

The collections: key sets the list of collections to search for short names, but roles do not inherit it: a role has its own search order — even if it has no list of its own in meta/main.yml. So in tasks it is more reliable to always write the FQCN.

Roles inside a collection always look for content in their own collection first: it is fine to use short names for neighbours within the package. Dependencies from meta/main.yml run before the role itself.

The galaxy commands are collected in the cheat sheet, section “Collections and roles”. Variables and their precedence are covered in the section “Variables and facts”, handlers and the order of a play’s tasks — in the section “Playbooks: plays, tasks and handlers”.

Section sources

the section is written from these pages

Security: Vault and become

Ansible Vault encrypts the secrets playbooks need: passwords and keys sit in encrypted files and variables right in the repository. The become mechanism grants root privileges on the managed nodes — through sudo or su. A plain-text password in vars or host key checking switched off undoes both measures.

What Vault encrypts

Vault encrypts individual variables and whole files. The ansible-vault encrypt_string command encrypts a variable: the file stays readable, and the secret inside it turns into a !vault block. A file is encrypted with ansible-vault create or encrypt: both the values and the variable names are hidden.

CriterionA variable (encrypt_string)A whole file (create, encrypt)
What is visible in the repositoryvariable names are readable, the secrets are encryptedthe whole file is gibberish
Changing the passwordnot possible: the values are created anewansible-vault rekey in a single run
When to choose ita few secrets among ordinary settingsthe whole file is secrets: passwords, keys
bashon the control node
# encrypt a single variableansible-vault encrypt_string \  --vault-password-file ~/.vault_pass \  'S3cr3t-p@ss' --name db_password
yamlexample output
db_password: !vault |      $ANSIBLE_VAULT;1.1;AES256      623133653966…306231386433626436623361      61343336653539…31643561

The file keeps the format header and the AES256 ciphertext; when encrypting with a label, the header also prints the vault ID. The finished block is pasted into a vars file or a playbook as an ordinary variable.

Vault ID and where the password comes from

A single password for everything suits a small team. With more environments, each set of secrets gets a label — a vault ID — and its own password: dev@... encrypts the development files, prod@... the production ones. The label is stored in the readable header of the ciphertext and reminds you which password is needed.

bashon the control node
# encrypt a file with the prod labelansible-vault encrypt \  --vault-id prod@~/.vault_pass_prod group_vars/prod.yml # a playbook with two passwordsansible-playbook --vault-id dev@~/.vault_pass_dev \  --vault-id prod@~/.vault_pass_prod site.yml

The password source is part of the entry: @prompt asks in the terminal, @file reads the password from a file, @script calls a client script that fetches the password from a secrets manager. Without a label the --ask-vault-pass and --vault-password-file flags work.

bashtwo ways without a vault ID
ansible-playbook --ask-vault-pass site.ymlansible-playbook --vault-password-file ~/.vault_pass site.yml

To avoid typing the password on every run, the path to the file is written in ansible.cfg into the vault_password_file setting or into the ANSIBLE_VAULT_PASSWORD_FILE environment variable. The source file can also be a script: Ansible takes the password from its output — this is how secrets managers are connected. By default the label is only a hint: Ansible tries every password it is given until one matches; the DEFAULT_VAULT_ID_MATCH setting allows decryption only when the label matches.

no_log: the log leaks too

The decrypted value lands in the task output: the CI log and the terminal history see the password even though it sits in Vault. no_log: true on a task removes its output. no_log silences diagnostics too — a failing task will have to be re-checked with the key turned off.

yamlplaybook
- name: Create the app user  community.postgresql.postgresql_user:    name: app    password: "{{ db_password }}"  no_log: true

become: root privileges on demand

Ansible connects as an ordinary user and escalates privileges where the become keyword asks for it. The default method is sudo, and the list of supported ones is wider: su, doas, pfexec and others. become_user sets the account to become: root by default, but an unprivileged account works too — for example, to work with the application’s files on its behalf.

yamlplaybook
- name: Ensure the nginx service is running  ansible.builtin.service:    name: nginx    state: started  become: true - name: Restart the app as its own user  ansible.builtin.systemd:    name: myapp    state: restarted  become: true  become_user: appuser

Ansible asks for the escalation password with the -K flag (--ask-become-pass); if a playbook “hangs”, it is most likely waiting for this input. Permanent settings are given as variables on a host or a group: ansible_become: true, ansible_become_user, ansible_become_method, the password — ansible_become_password, preferably from Vault.

A separate limitation of sudo: Ansible runs modules from temporary files with changing names, so a list of allowed commands in sudoers breaks the playbook. For such rules a dedicated account without restrictions is set aside.

SSH: keys and host key checking

By default Ansible expects SSH keys, not passwords: password authentication is switched on with the --ask-pass flag when there is no other way. Keys are kept in ssh-agent: Ansible does not pass the password that decrypts the key to the SSH process.

The second line of defence is host key checking; it is enabled by default and stops the server from being spoofed. When a host key does not match the entry in known_hosts — for example, after the node has been reinstalled — the playbook stops with an error; a new host asks to confirm the fingerprint, and from cron such a question would hang. Switching the check off (host_key_checking = False in ansible.cfg) opens the way to spoofing a node, so in production the check is not switched off: keys are updated in a controlled way, host by host.

Wrong and right

The same fragment of a playbook can be written as a leak or as protection.

yamldon’t do this
# do not do this: the password in git as plain text- name: Create the app user  ansible.builtin.user:    name: app    password: "SuperSecret123" - name: Install the package  ansible.builtin.apt:    name: htop  become: true  become_method: su
yamldo this instead
# do this instead: the secret from Vault, key-based login- name: Create the app user  ansible.builtin.user:    name: app    password: "{{ app_password | password_hash('sha512') }}"    update_password: on_create  no_log: true - name: Install the package  ansible.builtin.apt:    name: htop  become: true
  • secrets come from Vault, the Vault password stays outside the repository
  • tasks with secrets run under no_log: true
  • nodes are reached with SSH keys through ssh-agent
  • host key checking is not switched off
  • privileges are escalated with become per task, not the whole play under root

What exactly to configure on the server for protection — firewall, updates, file permissions — is described in the Linux server hardening reference, the section “Checklist”; this section is about automating it. SSH keys themselves are covered in the Linux reference, the section “Access and initial setup”.

Section sources

the section is written from these pages

Common errors and troubleshooting

Troubleshoot in stages: whether the host is reachable over SSH, whether the syntax check passes, what a run in check mode would change. Only then move on to verbose output and the task debugger: each step cuts away one layer of problems.

Checking order

  1. ansible all -m ping — a quick response from every host: the SSH login worked, Python is on the node and the module ran.
  2. ansible-playbook --syntax-check — YAML and playbook structure errors; tasks are not run.
  3. ansible-playbook --check --diff — what would change; changes are shown as a diff.
  4. ansible-playbook -vvv — verbose output of the run; -vvvv adds the SSH log.
  5. the task debugger — edit variables and arguments right on the failed task.

A host with a failed task, or an unreachable host, drops out of the play. To run tasks on it again within the same run, bring the dropped hosts back with the meta: clear_host_errors task; the count of dropped hosts remains in the unreachable= line of the PLAY RECAP.

Host UNREACHABLE

The cause: SSH did not come up — check the address and port (ansible_host, ansible_port), the ansible_user and the key Ansible uses to log in to the host. On a new host, answer the fingerprint prompt (known_hosts), and after a node is reinstalled, refresh its key.

bashon the control node
# response from every host in the inventoryansible all -i hosts.ini -m ping

For SSH debugging the -vvvv flag shows the command line and the connection log; repeat the same path by hand with an ssh command using the same options. When troubleshooting, host key checking is disabled last, and only briefly: see the section “Security: Vault and become”.

The playbook waits for a sudo password

The cause: a task with become needs a privilege escalation password, and Ansible never asked for it. Run the playbook with the -K flag (--ask-become-pass) — it prompts for the escalation password.

bashon the control node
ansible-playbook -i hosts.ini site.yml -b -K

A task always reports changed

The cause: the command and shell modules run their command on every invocation and cannot check state. Control the report with the changed_when key: it decides, from the task’s result, whether the task counts as a change.

yamlplaybook
- name: Report the change honestly  ansible.builtin.command: make install  register: build  changed_when: build.rc == 0

The changed_when: false key is useful for checks that change nothing — for example, so that a validator run does not wake the handlers. The command module also has a safety net, creates: the command runs only while the file is absent.

'wrong_var' is undefined

The cause: a typo in the name, or a variable defined in the wrong place. The command ansible db1 -i hosts.ini -m debug -a "var=hostvars['db1']" prints a specific host’s variables — and facts, if they have been gathered or sit in the cache. Substitute the host name from the inventory for db1. In the task, protect yourself with the default filter.

yamlplaybook
- name: Print port with a fallback  ansible.builtin.debug:    msg: "app listens on {{ app_port | default(8080) }}"

One variable — one place: agree within the project where each value lives. The -e flag (--extra-vars) overrides a value for a single run; how variables from different places win — in the section “Variables and facts”.

Python not found on the host

The cause: modules run on the managed node through Python, and interpreter autodetection (interpreter_python = auto) found no suitable one — for example, on a minimal image without Python or with a non-standard path. Set the interpreter with the ansible_python_interpreter variable in the inventory; it overrides autodetection.

iniinventory.ini
[servers]db1 ansible_host=192.0.2.10 [servers:vars]# path to Python for the modulesansible_python_interpreter=/usr/bin/python3

The ansible_python.executable fact from the gathered facts shows which interpreter was chosen in the end. How to get them — in the section “Variables and facts”.

Value checks: debug and assert

The debug module prints a variable or a message and helps you trace which value actually reached the task. The assert module fails the task when a condition from the that list is not met — that way the playbook itself catches invalid values.

yamlplaybook
- name: Show the resolved port  ansible.builtin.debug:    var: app_port - name: Fail on an impossible port  ansible.builtin.assert:    that:      - app_port | int > 0      - app_port | int <= 65535    fail_msg: "app_port must be a port number"

The task debugger

The debugger starts on a failed task and lets you inspect and fix arguments and variables without editing the playbook. It is disabled by default; enable it with a keyword on the task or with an environment variable.

yamlplaybook
- name: Install the package  ansible.builtin.apt:    name: "{{ pkg_name }}"  debugger: on_failed
bashon the control node
# enable the debugger for a single runexport ANSIBLE_ENABLE_TASK_DEBUGGER=Trueansible-playbook -i hosts.ini site.yml
CommandWhat it does
p task.argsshow the task arguments
task.args['name'] = 'nginx'replace an argument
p task_vars['pkg_name']show a variable
task_vars['pkg_name'] = 'nginx'replace a variable
redorun the task again
continuemove on to the next task

Minor symptoms

SymptomCauseWhat to do
the syntax check fails, but the file looks righttabs instead of spaces in YAMLrewrite the indentation with spaces, 2 per level
the host is listed in the output, the task is skippeda typo in the group name in hosts:check the selection with ansible-inventory --graph
a fact is empty although the host is upfact gathering is disabled or the cache is staleremove gather_facts: false or refresh the cache
the playbook keeps waiting for a sudo passwordthe task has become but no password was suppliedrun with -K or set ansible_become_password
every task reports changed after a releasea command task without changed_whendescribe the condition with changed_when

Debugging and reference commands are collected in the cheat sheet, the “Debugging and reference” group. Variable precedence is covered in detail in the section “Variables and facts”; become and keys — in the section “Security: Vault and become”.

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Ansible 14 — the community package built on the ansible-core 2.21 core. The latest package release is 14.6.0 of 4 November 2026, with ansible-core 2.21.6. Core 2.22.0 was released on 2 November 2026; Ansible 15, based on it, is still in development.

Two release lines

The project ships two products: ansible-core, the core with the playbook language, the executor and the bundled modules, and ansible, the community package: the same core plus a curated set of collections. A major version of the package comes out roughly twice a year, following a new core release: Ansible 14 is built on ansible-core 2.21. Minor releases of both lines come out every four weeks and carry only backwards-compatible changes.

Different numbers of versions are supported. The community package has one major version: when a new one comes out, the previous one goes out of support. ansible-core keeps three, on a staggered scheme: the newest release receives bug and security fixes; when the next one is released, it is left with security and critical bug fixes; after one more release — security fixes only.

The ansible-core support matrix

Dates are taken from the Releases and maintenance page. Each core version maps to its own major version of the package: 2.22 — Ansible 15, 2.21 — Ansible 14, 2.20 — Ansible 13. The table shows the dates from which each stage begins; from release to end of life about a year and a half passes. Core 2.19 goes out of support in November 2026.

VersionReleasedCritical and securitySecurity onlyEnd of supportControl node Python
2.222 November 2026from May 2027from November 2027May 20283.13–3.15
2.21May 2026from November 2026from May 2027November 20273.12–3.14
2.204 November 2025from 18 May 2026from 2 November 2026May 20273.12–3.14

What changed in Ansible 14

For the full list see the porting guide: every core and package release has one. The main changes in core 2.21 and package 14:

  • Password hashing: the password_hash filter and service-side encryption moved from the passlib library to libcrypt/libxcrypt. The hashes remain valid but no longer match, byte for byte, those issued by older versions; check any scripts that compare hashes.
  • Detecting failure from a non-zero rc without an explicit failed is deprecated: from ansible-core 2.22 it will produce warnings, and later the behaviour will be removed. Report failure explicitly — via failed: true or fail_json.
  • ansible-galaxy install no longer installs collections whose requires_ansible is incompatible with the running core; the COLLECTIONS_ON_ANSIBLE_VERSION_MISMATCH=ignore configuration setting restores the old behaviour.
  • The register keyword can map several variable names to Jinja expressions, which replaces set_fact in simple cases; conditions can use an implicit _task object holding the result of the current task.
  • PowerShell modules run on POSIX hosts through pwsh.
  • The deprecated ansible.builtin.paramiko connection plugin has been removed: the persistent and smart values of the connection keyword no longer switch to it.

Deprecated and removed

The composition of the package changes: collections are removed from it through a removal procedure, and playbooks keep using their fully qualified names (FQCN). Update them in advance:

  • Removed in 14.0.0: awx.awx, cisco.dnac, junipernetworks.junos. After removal, a collection is installed separately: ansible-galaxy collection install awx.awx.
  • Slated for removal in Ansible 16: cisco.ucs — development has stopped and its functionality has moved to cisco.intersight — and dellemc.unity.
  • Renamed: purestorage.flasharray to everpure.flasharray and purestorage.flashblade to everpure.flashblade. In Ansible 15 the old names keep working through redirections; in Ansible 17 the collections will be deleted.

How to upgrade

Read the porting guide for the target version, upgrade the package and run your playbooks in check mode: --check shows what a run would change without touching the managed nodes. Installation via pipx is described in “Installation and first run”.

bashon the control node
pipx upgrade --include-injected ansibleansible --versionansible-playbook site.yaml --check --diff

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Ansible” topic
13 sections
Another reference · DevOps & cloud

Docker

Verified 31 Oct
All references · 61