← Full reference

ansible

Ansible playbooks — structure, the user/file/copy/template/lineinfile modules, loops, conditions, idempotency, --check

Ansible describes the desired state of a system in a YAML file — a playbook — and brings machines to that state. Each task calls a module ("the user exists", "the line is in the file"), and the module decides on its own whether anything needs to change. Ansible usually connects to servers over SSH, but it can also work on the local machine.

Syntax

ansible-playbook [-i inventory] [options] playbook.yml
ansible <hosts> [-i inventory] -m module -a 'arguments'   # a single task without a playbook

Playbook structure:

- name: Description of the set of tasks   # play
  hosts: localhost                  # which hosts to run on
  connection: local                 # no SSH, right on this machine
  gather_facts: true                # collect facts about the system (ansible_facts)
  become: true                      # run via sudo
  vars:
    app_dir: /opt/app
  tasks:
    - name: Description of the task
      ansible.builtin.file:         # module
        path: "{{ app_dir }}"       # module parameters
        state: directory

ansible-playbook options

OptionWhat it does
-i fileinventory: list of hosts and groups (INI or YAML); -i localhost, — a list inline
-l patternlimit hosts (-l web, -l 'web:!db')
-e 'key=value' / -e @vars.ymlvariables with the highest precedence
--checkdry run: show what would change without changing anything
--diffshow file differences; together with --check — before applying
--syntax-checkonly check the syntax
--list-tasks / --list-hostswhich tasks / hosts will be affected
--tags t1,t2 / --skip-tags trun only / skip tasks with these tags
--start-at-task 'name'start at the given task
-b / -Kbecome / ask for the sudo password
-v, -vv, -vvvmore detail: module results, then connection details

Common modules

Full name — ansible.builtin.<module>; help — ansible-doc ansible.builtin.<module>, short form — ansible-doc -s ….

ModuleKey parametersWhat it does
username, state, shell, groups, append, create_home, removeuser exists / is removed
groupname, state, gidgroup
filepath, state (directory, touch, absent, link), owner, group, mode, srcdirectory, empty file, link, permissions, removal
copydest, src or content, owner, mode, backupa file with the given content
templatesrc (a Jinja2 .j2 template), dest, owner, modea file from a template with variables substituted
lineinfilepath, line, regexp, state, insertafter, createa single line in a file is present / replaced / removed
blockinfilepath, block, marker, createa block of lines between markers
replacepath, regexp, replaceregex replacement across the whole file
commandcmd, chdir, creates, removesrun a program (no shell: no |, >, *)
shellsamerun via sh — with pipes and redirections
package / aptname, state (present, absent, latest), update_cachepackages
servicename, state (started, stopped, restarted), enabledservice
cronname, minute, hour, job, user, statea crontab line
statpathinformation about a file (result via register)
get_url / unarchiveurl, dest / src, dest, remote_srcdownload a file / extract an archive
debugmsg or varprint a value
set_factname: valuedefine a variable during the playbook run
assertthat, fail_msgcheck conditions, fail otherwise

Task keys

KeyWhat it does
namedescription — shown in the output
looprepeat the task for each element; the current one is {{ item }}
loop_control.labelwhat to show in the output instead of the whole item
whenrun only if the condition is true (without {{ }})
registersave the module result into a variable (.rc, .stdout, .changed)
changed_when / failed_whenyour own rule for when the task counts as changed / failed
ignore_errors: truedon't stop if the task fails
notifyafter a change, trigger a handler from the handlers section
become / become_userrun as root / as the given user
tagstags for --tags / --skip-tags
check_modeforce the task to run in check mode (or the opposite)

At the play level, besides tasks, there are vars, vars_files (variables from files), handlers (tasks that run on notify, once, at the end) and roles. Variables for groups and hosts can be placed in group_vars/<group>.yml and host_vars/<host>.yml next to the inventory.

Examples

# check the syntax and see the task list
ansible-playbook site.yml --syntax-check
ansible-playbook site.yml --list-tasks

# dry run with file diffs, then the real run
ansible-playbook site.yml --check --diff
ansible-playbook site.yml

# override a variable from the command line
ansible-playbook site.yml -e app_dir=/srv/app

# with an inventory: host groups and connection method
ansible-playbook -i inventory.ini site.yml

# a single task without a playbook (ad hoc)
ansible localhost -m ansible.builtin.ping
ansible localhost -m ansible.builtin.setup -a 'filter=ansible_distribution*'

An inventory where the local machine is in the local group:

[local]
localhost ansible_connection=local

A playbook with a loop, a template, a condition and a handler:

- name: Configure the application
  hosts: localhost
  connection: local
  vars:
    app_user: demo
    app_dir: /opt/demo
  handlers:
    - name: show reload
      ansible.builtin.debug:
        msg: "config changed"
  tasks:
    - name: Application user
      ansible.builtin.user:
        name: "{{ app_user }}"
        shell: /bin/bash

    - name: Directories
      ansible.builtin.file:
        path: "{{ app_dir }}/{{ item }}"
        state: directory
        owner: "{{ app_user }}"
        mode: "0755"
      loop:
        - conf
        - logs

    - name: Setting in the config
      ansible.builtin.lineinfile:
        path: "{{ app_dir }}/conf/app.ini"
        regexp: '^port='
        line: "port=8080"
        create: true
      notify: show reload

    - name: Config from the template templates/app.conf.j2
      ansible.builtin.template:
        src: templates/app.conf.j2
        dest: "{{ app_dir }}/conf/app.conf"

    - name: Only on the Debian family
      ansible.builtin.debug:
        msg: "{{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}"
      when: ansible_facts['os_family'] == "Debian"

Idempotency

Running the same playbook again should change nothing: the final PLAY RECAP line will show changed=0. Modules like user, file, copy, lineinfile first check the current state and change only what differs. ok — already as it should be, changed — had to change something, skipped — the task was skipped (when, --check).

Pitfalls

  • command and shell always report changed and don't know whether they need to run. Add creates:/removes:, or changed_when: false for commands that only read.
  • state: touch in file is also always changed: it updates the file's timestamp on every run.
  • Two tasks edit the same line differently — and every run reports changed. If a repeat run changes something, look for such a conflict.
  • Write mode as a quoted string: mode: "0644". YAML reads the number 644 without a leading zero as decimal, and the permissions come out strange (1204).
  • Quote a value that starts with {{: path: "{{ dir }}/x". Without quotes YAML takes the curly brace as the start of a mapping and the playbook won't load.
  • when is written without {{ }} — it's already a Jinja2 expression.
  • --check doesn't run command/shell (they are skipped), so tasks that depend on their result may behave differently than in a real run.
  • No matching host is not an error. If hosts: matches no inventory group, Ansible prints a warning and silently does nothing. Check with --list-hosts.
  • Without -i there is no inventory, only the implicit localhost is available; the all group doesn't include it.
  • A handler runs once at the end of the play and only if the task that notified it was changed.

See also

ssh · yq · cron · useradd · terraform