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
| Option | What it does |
|---|---|
-i file | inventory: list of hosts and groups (INI or YAML); -i localhost, — a list inline |
-l pattern | limit hosts (-l web, -l 'web:!db') |
-e 'key=value' / -e @vars.yml | variables with the highest precedence |
--check | dry run: show what would change without changing anything |
--diff | show file differences; together with --check — before applying |
--syntax-check | only check the syntax |
--list-tasks / --list-hosts | which tasks / hosts will be affected |
--tags t1,t2 / --skip-tags t | run only / skip tasks with these tags |
--start-at-task 'name' | start at the given task |
-b / -K | become / ask for the sudo password |
-v, -vv, -vvv | more detail: module results, then connection details |
Common modules
Full name — ansible.builtin.<module>; help — ansible-doc ansible.builtin.<module>, short form — ansible-doc -s ….
| Module | Key parameters | What it does |
|---|---|---|
user | name, state, shell, groups, append, create_home, remove | user exists / is removed |
group | name, state, gid | group |
file | path, state (directory, touch, absent, link), owner, group, mode, src | directory, empty file, link, permissions, removal |
copy | dest, src or content, owner, mode, backup | a file with the given content |
template | src (a Jinja2 .j2 template), dest, owner, mode | a file from a template with variables substituted |
lineinfile | path, line, regexp, state, insertafter, create | a single line in a file is present / replaced / removed |
blockinfile | path, block, marker, create | a block of lines between markers |
replace | path, regexp, replace | regex replacement across the whole file |
command | cmd, chdir, creates, removes | run a program (no shell: no |, >, *) |
shell | same | run via sh — with pipes and redirections |
package / apt | name, state (present, absent, latest), update_cache | packages |
service | name, state (started, stopped, restarted), enabled | service |
cron | name, minute, hour, job, user, state | a crontab line |
stat | path | information about a file (result via register) |
get_url / unarchive | url, dest / src, dest, remote_src | download a file / extract an archive |
debug | msg or var | print a value |
set_fact | name: value | define a variable during the playbook run |
assert | that, fail_msg | check conditions, fail otherwise |
Task keys
| Key | What it does |
|---|---|
name | description — shown in the output |
loop | repeat the task for each element; the current one is {{ item }} |
loop_control.label | what to show in the output instead of the whole item |
when | run only if the condition is true (without {{ }}) |
register | save the module result into a variable (.rc, .stdout, .changed) |
changed_when / failed_when | your own rule for when the task counts as changed / failed |
ignore_errors: true | don't stop if the task fails |
notify | after a change, trigger a handler from the handlers section |
become / become_user | run as root / as the given user |
tags | tags for --tags / --skip-tags |
check_mode | force 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
commandandshellalways reportchangedand don't know whether they need to run. Addcreates:/removes:, orchanged_when: falsefor commands that only read.state: touchinfileis also alwayschanged: 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
modeas a quoted string:mode: "0644". YAML reads the number644without 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. whenis written without{{ }}— it's already a Jinja2 expression.--checkdoesn't runcommand/shell(they areskipped), 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
-ithere is no inventory, only the implicitlocalhostis available; theallgroup doesn't include it. - A handler runs once at the end of the play and only if the task that notified it was
changed.