Get started
Cheatsheet

Ansible

The Ansible commands, playbook and inventory snippets, modules, templates, roles and vault commands you reach for every day.

Practice this path

Ad-hoc commands

One module, once. -m picks the module, -a passes its arguments.

  • ansible localhost -m ping

    Check 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.copy

    Read a module's documentation offline (-s shows a short snippet)

  • ansible-doc -l | grep file

    List every installed module and filter the list

  • ansible-config dump --only-changed

    Show the settings that differ from the defaults, and where they came from

Running playbooks

  • ansible-playbook site.yml

    Run a playbook

  • ansible-playbook site.yml --syntax-check

    Parse the playbook and report errors without running anything

  • ansible-playbook site.yml --check --diff

    Dry run that shows what would change, line by line

  • ansible-playbook site.yml --limit web

    Run only for the hosts or groups matching the pattern

  • ansible-playbook site.yml --tags config

    Run only the tasks tagged config (--skip-tags does the opposite)

  • ansible-playbook site.yml --list-tasks

    List what would run (also --list-tags and --list-hosts)

  • ansible-playbook site.yml -e app_env=prod -e @vars.yml

    Set 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 -vvv

    More 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=8080

    An 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: 8080

    The same idea in YAML

  • ansible-inventory -i inventory.ini --graph

    Draw the groups and hosts as a tree

  • ansible-inventory -i inventory.ini --list --yaml

    Print everything Ansible understood, in YAML (convert a format with it)

  • ansible-inventory -i inventory.ini --host web2

    Show every variable of one host

  • [defaults]
    inventory = inventory.ini
    interpreter_python = auto_silent

    ansible.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.yml

    Play variables, and variables loaded from a file

  • - ansible.builtin.command: id -un
      register: who
    - ansible.builtin.debug:
        var: who.stdout

    Save 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.yml

    Files 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=false

    Make sure one line is present, replacing the line that matches regexp

  • - ansible.builtin.blockinfile:
        path: app.conf
        block: |
          [limits]
          max_clients=50

    Manage a block of lines between BEGIN/END ANSIBLE MANAGED BLOCK markers

  • - ansible.builtin.file:
        path: old.conf
        state: absent

    Delete 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 > 1

    Run a command, and decide yourself what counts as changed or failed

  • - ansible.builtin.stat:
        path: app.conf
      register: conf

    Read 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 1024

    Stop 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: 2

    Retry a task until it succeeds

  • block:
      - ansible.builtin.command: ./migrate.sh
    rescue:
      - ansible.builtin.debug:
          msg: rolling back
    always:
      - ansible.builtin.debug:
          msg: done

    Try, 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 app

    Render a Jinja2 file from variables (src is looked up in templates/)

  • handlers:
      - name: Reload app
        ansible.builtin.command: ./reload.sh

    A handler runs once at the end of the play, only if a task notified it and changed

  • - ansible.builtin.meta: flush_handlers

    Run 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/webapp

    Scaffold 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.yml

    Where each part of a role lives (defaults are the easiest to override)

  • roles:
      - webapp
      - role: webapp
        vars:
          webapp_port: 9090

    Use 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-tasks

    See 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.yml

    Encrypt a file in place

  • ansible-vault view --vault-password-file .vault_pass secrets.yml

    Read an encrypted file without decrypting it on disk

  • ansible-vault edit --vault-password-file .vault_pass secrets.yml

    Edit an encrypted file in your editor

  • ansible-vault decrypt --vault-password-file .vault_pass secrets.yml

    Turn an encrypted file back into plain text

  • ansible-vault rekey --vault-password-file old --new-vault-password-file new secrets.yml

    Change the password of an encrypted file

  • ansible-vault encrypt_string --vault-password-file .vault_pass 'S3cret' --name db_password

    Encrypt one value and print a ready-to-paste variable

  • ansible-playbook site.yml --vault-password-file .vault_pass

    Run a playbook that uses encrypted files (--ask-vault-pass prompts instead)

  • [defaults]
    vault_password_file = .vault_pass

    Set the password file once in ansible.cfg so no flag is needed

Cheatsheet for the Ansible path · Deboistech · All cheatsheets