Ansible Cheat Sheet
Ansible connects to the hosts from an inventory over SSH and runs tasks, each calling a module that describes a desired state (“package installed”, “file present”). Running the same playbook twice changes nothing the second time.
flowchart LR inv[Inventory] --> play[Playbook] play --> tasks[Tasks] tasks -->|SSH| h1[web1] tasks -->|SSH| h2[web2]
Building blocks
Section titled “Building blocks”all: children: webservers: hosts: web1: ansible_host: 192.168.1.101 web2: ansible_host: 192.168.1.102 vars: http_port: 80- name: Set up web servers hosts: webservers become: true # run tasks with sudo tasks: - name: Install nginx ansible.builtin.package: name: nginx state: present
- name: Deploy the config ansible.builtin.template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: Reload nginx # handler runs once at the end, only if this task changed something
handlers: - name: Reload nginx ansible.builtin.service: name: nginx state: reloadedA role packages tasks, handlers, templates and variables for reuse. Only the directories you need have to exist; Ansible
loads each main.yml automatically.
defaults/main.yml # default variables, lowest precedencetasks/main.yml # the taskshandlers/main.yml # handlerstemplates/ # Jinja2 templates for the template modulefiles/ # static files for the copy modulemeta/main.yml # dependencies and argument specsMy own roles are documented under Ansible Collections.
Variable precedence
Section titled “Variable precedence”When the same variable is defined in several places, the later source in this list wins (simplified):
- role
defaults/ - inventory
group_vars(allfirst, then more specific groups) - inventory
host_vars - play
vars - role
vars/ - task
vars - extra vars (
-e), which always win
Commands
Section titled “Commands”| Command | Effect |
|---|---|
ansible-playbook -i inventory.yml site.yml |
Runs a playbook. |
ansible-playbook site.yml --check --diff |
Dry run that shows what would change. |
ansible-playbook site.yml --limit web1 |
Runs only on some hosts. |
ansible-playbook site.yml --tags nginx |
Runs only tasks with that tag. |
ansible-playbook site.yml -K |
Asks for the sudo password (become). |
ansible-playbook site.yml -e http_port=8080 |
Sets a variable with the highest precedence. |
ansible webservers -m ping |
Ad-hoc module call, here a connection test. |
ansible all -m setup -a 'filter=ansible_distribution*' |
Shows gathered facts. |
ansible-inventory --graph |
The inventory as a tree of groups and hosts. |
ansible-doc ansible.builtin.template |
Documentation and examples of a module. |
ansible-vault encrypt secrets.yml |
Encrypts a file; run playbooks with --ask-vault-pass. |
ansible-galaxy collection install community.general |
Installs a collection (-r requirements.yml for a list). |
ansible-galaxy role init webserver |
Creates the role directory skeleton. |