Ansible
The Ansible commands, playbook and inventory snippets, modules, templates, roles and vault commands you reach for every day.
Ad-hoc commands
One module, once. -m picks the module, -a passes its arguments.
ansible localhost -m pingCheck that Ansible can run a module on a host (answers pong)
ansible all -i inventory.ini -m ansible.builtin.command -a "uptime"Run a command on every host of an inventory
ansible web -m ansible.builtin.file -a "path=/tmp/data state=directory mode=0750"Create a directory on the hosts of the group web
ansible localhost -m ansible.builtin.setup -a "filter=ansible_distribution*"Print the facts whose name starts with ansible_distribution
ansible-doc ansible.builtin.copyRead a module's documentation offline (-s shows a short snippet)
ansible-doc -l | grep fileList every installed module and filter the list
ansible-config dump --only-changedShow the settings that differ from the defaults, and where they came from
Running playbooks
ansible-playbook site.ymlRun a playbook
ansible-playbook site.yml --syntax-checkParse the playbook and report errors without running anything
ansible-playbook site.yml --check --diffDry run that shows what would change, line by line
ansible-playbook site.yml --limit webRun only for the hosts or groups matching the pattern
ansible-playbook site.yml --tags configRun only the tasks tagged config (--skip-tags does the opposite)
ansible-playbook site.yml --list-tasksList what would run (also --list-tags and --list-hosts)
ansible-playbook site.yml -e app_env=prod -e @vars.ymlSet variables from the command line or from a file (they beat every other source)
ansible-playbook site.yml --start-at-task "Write the config"Resume a run at the task with that name
ansible-playbook site.yml -vvvMore detail, up to -vvvv, when a task misbehaves
Inventory
[web] web1 web2 http_port=9090 [db] db1 [prod:children] web db [web:vars] http_port=8080An INI inventory with two groups, a parent group, a host variable and a group variable
all: children: web: hosts: web1: web2: http_port: 9090 vars: http_port: 8080The same idea in YAML
ansible-inventory -i inventory.ini --graphDraw the groups and hosts as a tree
ansible-inventory -i inventory.ini --list --yamlPrint everything Ansible understood, in YAML (convert a format with it)
ansible-inventory -i inventory.ini --host web2Show every variable of one host
[defaults] inventory = inventory.ini interpreter_python = auto_silentansible.cfg in the current folder, so you can leave out -i
Playbook basics
--- - name: Configure the app hosts: web gather_facts: false tasks: - name: Create the directory ansible.builtin.file: path: /srv/app state: directory mode: "0755"The shape of a playbook: a play, its hosts and a list of tasks
vars: app_name: demo vars_files: - vars/prod.ymlPlay variables, and variables loaded from a file
- ansible.builtin.command: id -un register: who - ansible.builtin.debug: var: who.stdoutSave a task's result with register and print it
- ansible.builtin.set_fact: full_name: "{{ app_name }}-{{ app_env }}"Create a variable while the play runs
group_vars/all.yml group_vars/web.yml host_vars/web1.ymlFiles next to the playbook that set variables for a group or one host (host_vars wins)
{{ ansible_facts.os_family }} {{ ansible_facts.distribution }} {{ ansible_facts.architecture }}Common facts (needs gather_facts, which is on by default)
Everyday modules
- ansible.builtin.copy: src: files/index.html dest: /srv/app/index.html mode: "0644"Copy a file (or write text with content:)
- ansible.builtin.lineinfile: path: app.conf regexp: '^debug=' line: debug=falseMake sure one line is present, replacing the line that matches regexp
- ansible.builtin.blockinfile: path: app.conf block: | [limits] max_clients=50Manage a block of lines between BEGIN/END ANSIBLE MANAGED BLOCK markers
- ansible.builtin.file: path: old.conf state: absentDelete a file or directory (state: directory, touch, link and absent are the main states)
- ansible.builtin.command: ./migrate.sh register: result changed_when: false failed_when: result.rc > 1Run a command, and decide yourself what counts as changed or failed
- ansible.builtin.stat: path: app.conf register: confRead file facts, then use conf.stat.exists or conf.stat.mode
- ansible.builtin.assert: that: - app_port | int > 1024 fail_msg: app_port must be above 1024Stop early with a clear message when an assumption is false
Loops, conditions and errors
- ansible.builtin.file: path: "dirs/{{ item }}" state: directory loop: [web, api, worker]Repeat a task once per list item
loop: "{{ apps }}" loop_control: label: "{{ item.name }}"Loop over dictionaries and keep the output short with label
when: ansible_facts.os_family == "Debian" and app_env == "prod"Run a task only when the condition holds (no braces; combine with and, or, not)
register: result until: result.rc == 0 retries: 5 delay: 2Retry a task until it succeeds
block: - ansible.builtin.command: ./migrate.sh rescue: - ansible.builtin.debug: msg: rolling back always: - ansible.builtin.debug: msg: doneTry, recover and always clean up (try / catch / finally)
tags: [config]Label a task so --tags config runs it alone
Templates and handlers
- ansible.builtin.template: src: app.conf.j2 dest: /etc/app.conf mode: "0644" notify: Reload appRender a Jinja2 file from variables (src is looked up in templates/)
handlers: - name: Reload app ansible.builtin.command: ./reload.shA handler runs once at the end of the play, only if a task notified it and changed
- ansible.builtin.meta: flush_handlersRun the pending handlers now instead of at the end of the play
# {{ ansible_managed }}First line of a template: marks the file as generated
{{ name | upper }} {{ timeout | default(30) }} {{ items | join(", ") }}Filters: change case, supply a default, join a list
{% for b in backends %} server {{ b }}:8080; {% endfor %}Repeat lines for every item of a list
{% if workers > 2 %} mode = cluster {% else %} mode = single {% endif %}Choose lines with if / else
Roles
ansible-galaxy role init roles/webappScaffold a role (tasks, handlers, defaults, templates, vars, meta, files, tests)
roles/webapp/ tasks/main.yml handlers/main.yml defaults/main.yml vars/main.yml templates/ files/ meta/main.ymlWhere each part of a role lives (defaults are the easiest to override)
roles: - webapp - role: webapp vars: webapp_port: 9090Use a role in a play, with and without parameters
- ansible.builtin.import_tasks: common.yml - ansible.builtin.include_tasks: "{{ ansible_facts.os_family }}.yml"Reuse a task file (import is static, include is decided while running)
ansible-playbook site.yml --list-tasksSee which tasks a role contributes, in order
Vault
Never commit the password file; put it in .gitignore.
ansible-vault encrypt --vault-password-file .vault_pass secrets.ymlEncrypt a file in place
ansible-vault view --vault-password-file .vault_pass secrets.ymlRead an encrypted file without decrypting it on disk
ansible-vault edit --vault-password-file .vault_pass secrets.ymlEdit an encrypted file in your editor
ansible-vault decrypt --vault-password-file .vault_pass secrets.ymlTurn an encrypted file back into plain text
ansible-vault rekey --vault-password-file old --new-vault-password-file new secrets.ymlChange the password of an encrypted file
ansible-vault encrypt_string --vault-password-file .vault_pass 'S3cret' --name db_passwordEncrypt one value and print a ready-to-paste variable
ansible-playbook site.yml --vault-password-file .vault_passRun a playbook that uses encrypted files (--ask-vault-pass prompts instead)
[defaults] vault_password_file = .vault_passSet the password file once in ansible.cfg so no flag is needed
Nothing matches that search.
Cheatsheet for the Ansible path · Deboistech · All cheatsheets
