Skip to content
abdallahmekky

CHEAT SHEET

Ansible cheat sheet

Everything for the RHCE road: inventory, playbooks, the modules you use most, roles and Vault. Use the module names in full (FQCN).

All cheat sheets

Ad hoc commands and docs

ansible all -m ping -i inventory                                          # can I reach every host?ansible web -m ansible.builtin.dnf -a "name=httpd state=present" -b       # install a package (-b = become)ansible all -a "uptime"                                                   # run a command (command module)ansible all -m ansible.builtin.setup -a "filter=ansible_distribution*"    # gather factsansible-inventory -i inventory --graph                                    # groups and hosts as a treeansible-doc ansible.builtin.dnf                                           # module documentationansible-doc -s ansible.builtin.dnf                                        # a snippet to copyansible-doc -l | grep firewalld                                           # find a module by name

Inventory

[web]node1.example.comnode2.example.com[db]node3.example.com ansible_user=admin[prod:children]webdb[all:vars]ansible_python_interpreter=/usr/bin/python3

ansible.cfg

[defaults]inventory = ./inventoryremote_user = devopsroles_path = ./roles[privilege_escalation]become = Truebecome_method = sudobecome_ask_pass = False

Ansible reads ./ansible.cfg first, then ~/.ansible.cfg, then /etc/ansible/ansible.cfg. ansible --version shows which one is active.

A playbook

---- name: Configure web servers  hosts: web  become: true  vars:    pkg: httpd  tasks:    - name: Install the package      ansible.builtin.dnf:        name: "{{ pkg }}"        state: present    - name: Start and enable the service      ansible.builtin.service:        name: httpd        state: started        enabled: true    - name: Open the firewall      ansible.posix.firewalld:        service: http        permanent: true        immediate: true        state: enabled
ansible-playbook site.yml                    # run itansible-playbook site.yml --syntax-check     # check the syntax onlyansible-playbook site.yml --check --diff     # dry run, show what would changeansible-playbook site.yml -l node1           # only one host or groupansible-playbook site.yml -t packages        # only tasks with a tagansible-playbook site.yml -e "pkg=nginx"     # override a variableansible-playbook site.yml --list-tasks       # show the tasks without runningansible-playbook site.yml -vvv               # more detail when debugging

Modules you will use most

ModuleUsed for
ansible.builtin.dnfInstall, update and remove packages
ansible.builtin.serviceStart, stop and enable services
ansible.builtin.copyCopy a file or write content to a file
ansible.builtin.templateRender a Jinja2 template to a file
ansible.builtin.fileCreate folders and links, set permissions
ansible.builtin.lineinfileMake sure one line is (or is not) in a file
ansible.builtin.user / groupManage users and groups
ansible.builtin.command / shellRun commands (prefer a real module)
ansible.builtin.cronManage cron jobs
ansible.builtin.debugPrint a message or a variable
ansible.builtin.statGather facts about a file
ansible.builtin.rebootReboot and wait for the host
ansible.posix.firewalldManage firewalld
ansible.posix.selinux / sebooleanSELinux mode and booleans
ansible.posix.mountManage mounts and fstab
community.general.lvg / lvolLVM volume groups and logical volumes
community.general.filesystemCreate a file system
community.general.partedManage partitions

Variables, facts and templates

- name: Show a few facts  ansible.builtin.debug:    msg: "{{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_major_version'] }} on {{ inventory_hostname }}"- name: Render a template  ansible.builtin.template:    src: motd.j2    dest: /etc/motd    mode: "0644"
Welcome to {{ inventory_hostname }}{% for user in users %}Account: {{ user }}{% endfor %}

Variable precedence, lowest to highest: role defaults, inventory, play vars, task vars, then -e extra vars always win.

Loops and conditionals

- name: Create users  ansible.builtin.user:    name: "{{ item }}"    state: present  loop:    - alice    - bob  when: ansible_facts['os_family'] == "RedHat"

Handlers

tasks:  - name: Update the config    ansible.builtin.template:      src: httpd.conf.j2      dest: /etc/httpd/conf/httpd.conf    notify: Restart httpdhandlers:  - name: Restart httpd    ansible.builtin.service:      name: httpd      state: restarted

A handler runs once, at the end of the play, and only if a task that notifies it actually changed something.

Error handling

- name: Try something risky  block:    - name: This fails      ansible.builtin.command: /bin/false  rescue:    - name: Recover      ansible.builtin.debug:        msg: "it failed, recovering"  always:    - name: Runs either way      ansible.builtin.debug:        msg: "cleanup"- name: Do not stop on this one  ansible.builtin.command: /bin/false  ignore_errors: true

Roles and collections

ansible-galaxy role init webserver                 # create a role skeletonansible-galaxy collection install ansible.posix    # install a collectionansible-galaxy collection list                     # what is installedansible-galaxy install -r requirements.yml         # install everything listed in a file
webserver/  tasks/main.yml        # the tasks  handlers/main.yml     # handlers  templates/            # Jinja2 templates  files/                # static files  defaults/main.yml     # lowest-priority variables  vars/main.yml         # higher-priority variables  meta/main.yml         # dependencies and metadata
---- name: Use a role  hosts: web  become: true  roles:    - webserver

Ansible Vault

ansible-vault create secret.yml                  # create an encrypted fileansible-vault edit secret.yml                    # edit itansible-vault view secret.yml                    # read itansible-vault encrypt vars.yml                   # encrypt an existing fileansible-vault decrypt vars.yml                   # decrypt itansible-vault rekey secret.yml                   # change the passwordansible-vault encrypt_string 'value' --name 'db_password'    # one encrypted variableansible-playbook site.yml --ask-vault-pass       # run with a typed passwordansible-playbook site.yml --vault-password-file ~/.vault_pass    # or a password file

More cheat sheets

Questions

How do I run an Ansible playbook?

Use ansible-playbook site.yml. Add --syntax-check to check it, --check --diff for a dry run and -i inventory to choose the inventory.

How do I see the documentation of a module offline?

Run ansible-doc ansible.builtin.dnf. ansible-doc -s MODULE prints a short playbook snippet to copy.

How do I encrypt a secret with Ansible Vault?

Use ansible-vault create secret.yml, or ansible-vault encrypt_string 'value' --name 'db_password' for a single variable. Run the playbook with --ask-vault-pass.

What does become: true do?

It runs tasks with privilege escalation, normally sudo to root, which most administration tasks need.