सामग्री पर जाएँ

लेसन 29 · Practice and Review

Ansible Cheat Sheet

One-page Ansible cheat sheet: CLI flags, inventory patterns, playbook keywords, common modules, Jinja2 filters, project layout, magic variables and ansible-vault commands.

This page is a quick reference for the things you look up most often while writing Ansible: command-line flags, inventory host patterns, playbook keywords, everyday modules, Jinja2 filters, directory layout, special variables and Vault commands. It assumes you know the ideas already; each section links to the lesson that explains them.

Ansible itself cannot run on this site, so every command and snippet is read-only. Two runnable stand-ins at the end of the relevant sections model host patterns and Jinja2 filters, so you can try the rules on sample data. They are models, not Ansible.

flowchart TD
  Q["What do I want to do?"] --> A["Run one module once<br/>ansible"]
  Q --> B["Run a playbook<br/>ansible-playbook"]
  Q --> C["Look at inventory<br/>ansible-inventory"]
  Q --> D["Read module docs<br/>ansible-doc"]
  Q --> E["Install roles and collections<br/>ansible-galaxy"]
  Q --> F["Encrypt secrets<br/>ansible-vault"]
  Q --> G["Check style and best practices<br/>ansible-lint"]

Seven commands cover almost everything; pick by what you want to do.

Command line

ad-hoc: ansible

Terminal
ansible <pattern> -m <module> -a "<arguments>" [options]
ansible all -m ansible.builtin.ping
ansible web -b -m ansible.builtin.service -a "name=nginx state=restarted"

playbooks: ansible-playbook

Terminal
ansible-playbook [-i inventory] site.yml [options]
Flag Meaning
-i, --inventory Inventory file, directory or comma-separated host list (-i "host1,")
-l, --limit Run only on hosts matching a pattern
-e, --extra-vars Extra variables: -e "key=value", -e @vars.yml or JSON
-t, --tags / --skip-tags Run or skip tagged tasks
-C, --check Dry run: predict changes without applying
-D, --diff Show file differences (combine with --check)
-b, --become Escalate privileges
-K, --ask-become-pass Prompt for the become password
-k, --ask-pass Prompt for the SSH password
-u, --user Remote user
--private-key SSH private key file
-f, --forks Parallel hosts (default 5)
-v to -vvvv More detail: results, task paths, connections, connection debugging
--syntax-check Parse only
--list-hosts, --list-tasks, --list-tags Show what would run, without running
--start-at-task "name" Begin at a named task
--step Confirm each task
--ask-vault-pass, --vault-password-file, --vault-id Unlock vaulted content

Ad-hoc commands accept most of these, plus -m, -a and -o (one-line output).

other tools

Command Use
ansible-inventory -i inv --list Whole inventory as JSON
ansible-inventory -i inv --graph Groups and hosts as a tree
ansible-inventory -i inv --host web1 All variables for one host
ansible-doc -l List modules; ansible-doc ansible.builtin.copy shows one (add -s for a short snippet)
ansible-config dump --only-changed Settings that differ from the defaults
ansible-galaxy init <role> Create a role skeleton
ansible-galaxy install -r requirements.yml Install roles and collections listed in a requirements file
ansible-galaxy collection install community.general Install a collection
ansible-lint Check playbooks and roles against best-practice rules

Inventory patterns

Pattern Selects
all or * Every host
web The group web (or a host called web)
web:db Hosts in web or db
web:&prod Hosts in web and prod
all:!db Everyone except db
web1,web2 Listed hosts (comma works like a colon)
web* Wildcard on names
~web[0-9]+ Regular expression (starts with ~)
web[0], web[-1] First or last host in the group

Combine them from left to right: web:db:&prod:!web3. See Inventory: Hosts and Groups. Run the model below to see unions, intersections and exclusions on a small inventory.

JS Host patterns on a small inventory

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The model applies all unions first, then each & filter, then each ! filter. That matches how Ansible resolves patterns for the simple cases shown here. Regular expressions and index ranges are left out.

Inventory file shapes

INI
[web]
web1 ansible_host=10.0.0.11 ansible_user=deploy
web2

[db]
db1

[prod:children]
web
db

[web:vars]
http_port=8080
YAML
all:
  children:
    web:
      hosts:
        web1:
          ansible_host: 10.0.0.11
        web2:
      vars:
        http_port: 8080

Connection variables you will use often: ansible_host, ansible_port, ansible_user, ansible_connection (ssh, local, winrm), ansible_ssh_private_key_file, ansible_become, ansible_python_interpreter.

Playbook keywords

A minimal play and the keywords you meet most:

YAML
- name: Configure web servers
  hosts: web
  become: true
  gather_facts: true
  vars:
    http_port: 8080
  pre_tasks: []
  roles: []
  tasks:
    - name: Install nginx
      ansible.builtin.package:
        name: nginx
        state: present
      notify: Reload nginx
      tags: [nginx]
  post_tasks: []
  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded
Level Keywords
Play name, hosts, become, become_user, remote_user, gather_facts, vars, vars_files, vars_prompt, roles, pre_tasks, tasks, post_tasks, handlers, serial, strategy, any_errors_fatal, max_fail_percentage, environment, connection, collections, force_handlers
Task name, when, loop, loop_control, register, notify, tags, vars, args, changed_when, failed_when, ignore_errors, until/retries/delay, delegate_to, run_once, no_log, become, check_mode, diff, environment, throttle, async/poll
Block block, rescue, always, plus any task keyword applied to the whole group

Control flow in a few lines:

YAML
- name: Create users
  ansible.builtin.user:
    name: "{{ item }}"
  loop: [alice, bob]
  when: ansible_facts['os_family'] == 'Debian'

- name: Wait for the app
  ansible.builtin.uri:
    url: "http://localhost:8080/health"
  register: health
  until: health.status == 200
  retries: 10
  delay: 3

- block:
    - name: Risky step
      ansible.builtin.command: /opt/app/migrate
  rescue:
    - name: Roll back
      ansible.builtin.command: /opt/app/rollback
  always:
    - name: Report
      ansible.builtin.debug:
        msg: "finished"

Other task-control tools: meta: flush_handlers, import_tasks / include_tasks, import_role / include_role.

Common modules

All names are shown in fully qualified form. Modules marked with ansible.posix or community.general come from collections you may need to install.

Job Module
Test connection ansible.builtin.ping
Run a program ansible.builtin.command, ansible.builtin.shell, ansible.builtin.raw, ansible.builtin.script
Copy a file ansible.builtin.copy
Render a template ansible.builtin.template
Files, directories, links, permissions ansible.builtin.file
Edit one line / a block / a regex ansible.builtin.lineinfile, ansible.builtin.blockinfile, ansible.builtin.replace
File information ansible.builtin.stat, ansible.builtin.find
Download / unpack ansible.builtin.get_url, ansible.builtin.unarchive
Git checkout ansible.builtin.git
Packages ansible.builtin.package, ansible.builtin.apt, ansible.builtin.dnf
Users and groups ansible.builtin.user, ansible.builtin.group, ansible.posix.authorized_key
Services ansible.builtin.service, ansible.builtin.systemd
Scheduled jobs ansible.builtin.cron
Wait and check ansible.builtin.wait_for, ansible.builtin.uri, ansible.builtin.reboot
Kernel and mounts ansible.posix.sysctl, ansible.posix.mount, ansible.builtin.hostname
Firewall ansible.posix.firewalld, community.general.ufw
Variables and flow ansible.builtin.set_fact, ansible.builtin.include_vars, ansible.builtin.debug, ansible.builtin.assert, ansible.builtin.fail, ansible.builtin.meta

Make commands honest: creates:, removes:, changed_when: false, failed_when: <expression>. See Modules and Idempotence.

Jinja2 and filters

Expression Result
{{ var }} Insert a value
{{ var | default('x') }} Use x when var is undefined (add true as a second argument to also replace empty values)
{{ list | join(', ') }} Join with a separator
{{ list | map(attribute='name') | list }} Pull one attribute from each item
{{ list | selectattr('admin') }} Keep items whose attribute is truthy
{{ list | unique | sort }} Remove duplicates and sort
{{ list | length }}, first, last Size, first, last
{{ text | upper }}, lower, replace('a','b') Text changes
{{ value | int }}, float, bool Type conversion
{{ dict | to_json }}, to_nice_yaml Serialise data
{{ cond | ternary('yes', 'no') }} Inline choice
{{ path | basename }}, dirname Path parts
{{ secret | password_hash('sha512') }} Hash a password
{% for h in groups['web'] %}...{% endfor %} Loop in a template
{% if x %}...{% else %}...{% endif %} Condition in a template

In YAML, a value that starts with {{ must be quoted. A tilde ~ joins strings: "{{ a ~ b }}". This stand-in models several filters in JavaScript and prints the result of each matching template expression, which is a quick way to check how a chain behaves. See Jinja2 Templates and Filters.

JS Jinja2 filter chains

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Project layout

TEXT
project/
  ansible.cfg
  requirements.yml            # roles and collections to install
  site.yml                    # main playbook
  playbooks/
    deploy.yml
  inventories/
    prod/
      hosts.yml
      group_vars/
        all.yml
        web.yml
        db/
          vars.yml
          vault.yml           # encrypted
      host_vars/
        web1.yml
    staging/
      hosts.yml
  roles/
    nginx/
      defaults/main.yml       # lowest precedence, meant to be overridden
      vars/main.yml           # high precedence, internal constants
      tasks/main.yml
      handlers/main.yml
      templates/              # .j2 files
      files/                  # static files
      meta/main.yml           # dependencies and metadata

A minimal ansible.cfg:

INI
[defaults]
inventory = inventories/prod/hosts.yml
roles_path = roles
forks = 10
host_key_checking = True

[privilege_escalation]
become = False

See Roles and Project Layout and Collections, Galaxy and Reusable Content.

Variable precedence (short list)

From weakest to strongest, the layers you meet daily:

  1. Role defaults/main.yml
  2. Inventory group_vars/all, then group_vars/<group>
  3. Inventory host_vars/<host>
  4. Play vars and vars_files
  5. Role vars/main.yml, block and task vars
  6. set_fact and register
  7. Extra vars, -e (always wins)

More detail in Variables, Facts and Precedence.

Magic variables

Variable Contains
inventory_hostname The host's name as written in the inventory
groups Dictionary of group name to list of hosts
group_names Groups the current host belongs to
hostvars Variables of every host: hostvars['db1']['ansible_host']
ansible_facts Gathered facts for the current host
ansible_check_mode true when running with --check
ansible_play_hosts Hosts still active in the current play
playbook_dir, role_path Paths of the playbook and the current role

Vault

Terminal
ansible-vault create secrets.yml           # new encrypted file
ansible-vault encrypt vars.yml             # encrypt in place
ansible-vault decrypt vars.yml             # decrypt in place
ansible-vault edit secrets.yml             # decrypt, edit, re-encrypt
ansible-vault view secrets.yml             # print decrypted content
ansible-vault rekey secrets.yml            # change the password
ansible-vault encrypt_string 'value' --name 'db_password'

ansible-playbook site.yml --ask-vault-pass
ansible-playbook site.yml --vault-password-file ~/.vault_pass
ansible-playbook site.yml --vault-id prod@~/.vault_prod

Add no_log: true to tasks that handle secrets, and keep password files out of git. See Ansible Vault and Secrets.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which pattern selects the hosts that are in both the web group and the prod group?

    A colon means union, :& means intersection and :! means exclusion. A comma also separates hosts, which gives the union.
  2. 2. Which command shows all variables Ansible has for the host web1?

    ansible-inventory --host prints the merged variables from the inventory for one host, which helps with precedence questions.
  3. 3. Which flag pair gives you a safe preview of what a playbook would change?

    --check predicts changes without applying them, and --diff shows the file differences.
  4. 4. In a role, which directory holds values that callers are expected to override?

    defaults/main.yml has the lowest precedence on purpose, so group_vars, host_vars and the play can override it.

Summary

  • ansible runs one module, ansible-playbook runs playbooks, and ansible-inventory, ansible-doc, ansible-galaxy, ansible-vault and ansible-lint cover inspection, documentation, sharing, secrets and style.
  • Host patterns combine with : (or), :& (and), :! (not) and wildcards; use -l to limit a run.
  • --check --diff previews a run, --syntax-check parses only and -v to -vvvv adds detail.
  • Prefer full module names, loop and handlers, and guard commands with creates, removes and changed_when.
  • Quote YAML values that start with {{, and use filters such as default, join, map and selectattr.
  • Role defaults are the weakest variables and -e is the strongest; secrets belong in Vault with no_log: true.

You have reached the end of the Ansible track. Review the weak spots with Exercises with Solutions, or revisit the beginning at What Is Ansible?.

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।