Ansible Cheat Sheet
Reference for Ansible playbook YAML syntax, inventory files, common modules, and ad-hoc command usage for configuration management.
Basic Playbook
A playbook installing and starting nginx on web servers.
---- name: Configure web servers hosts: webservers become: true vars: http_port: 80 tasks: - name: Install nginx apt: name: nginx state: present update_cache: true - name: Start nginx service: name: nginx state: started enabled: true - name: Copy config template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: restart nginx handlers: - name: restart nginx service: name: nginx state: restarted
Inventory File
INI-style inventory grouping hosts.
[webservers]web1.example.comweb2.example.com ansible_user=deploy[dbservers]db1.example.com[production:children]webserversdbservers[all:vars]ansible_ssh_private_key_file=~/.ssh/id_rsa
Ad-Hoc Commands & CLI
Common ansible and ansible-playbook CLI usage.
ansible all -m ping # Check connectivityansible webservers -a "uptime" # Run raw commandansible-playbook site.yml # Run a playbookansible-playbook site.yml --check # Dry runansible-playbook site.yml -i inventory --tags deployansible-galaxy install geerlingguy.nginx # Install a role
Common Modules
Frequently used built-in Ansible modules.
- apt / yum- Manage packages on Debian-based or RHEL-based systems
- copy / template- Copy files, or render Jinja2 templates, to remote hosts
- service / systemd- Manage and enable system services
- file- Manage file/directory state, permissions, and symlinks
- user / group- Manage user accounts and groups
- lineinfile- Ensure a particular line exists (or is absent) in a file
Role Directory Structure
Standard layout ansible-galaxy init generates for a reusable role.
roles/nginx/├── defaults/main.yml # Lowest-precedence variables├── vars/main.yml # Higher-precedence variables├── tasks/main.yml # Task list included when role runs├── handlers/main.yml # Handlers notified by this role's tasks├── templates/nginx.conf.j2├── files/robots.txt├── meta/main.yml # Role dependencies and Galaxy metadata└── tests/test.yml# Use it in a playbook:# - hosts: webservers# roles:# - role: nginx# vars:# http_port: 8080
Loops, Conditionals & register
Iterate over a list, capture task output, and branch on the result in a later task.
- name: Install a list of packages apt: name: "{{ item }}" state: present loop: - nginx - curl - git- name: Check if app is already deployed stat: path: /opt/app/current register: app_dir- name: Deploy application command: /opt/app/deploy.sh when: not app_dir.stat.exists- name: Restart only on Debian family service: name: nginx state: restarted when: ansible_facts['os_family'] == "Debian"
Error Handling with block/rescue/always
Group tasks and recover from failures the way try/catch/finally works in a general-purpose language.
- name: Attempt a risky deployment block: - name: Pull new release git: repo: "https://example.com/app.git" dest: /opt/app - name: Run migrations command: /opt/app/migrate.sh rescue: - name: Roll back to previous release command: /opt/app/rollback.sh always: - name: Notify deployment status uri: url: https://hooks.example.com/notify method: POST
ansible.cfg Essentials
Project-level configuration that overrides Ansible's defaults for performance and usability.
[defaults]inventory = ./inventoryremote_user = deployhost_key_checking = Falseretry_files_enabled = Falseroles_path = ./rolesforks = 20[ssh_connection]pipelining = Truecontrol_path = %(directory)s/%%h-%%r
Jinja2 Filters & Templating
Commonly used filters for transforming variables inside templates and task arguments.
- default(value)- Falls back to 'value' when the variable is undefined, e.g. {{ port | default(80) }}
- to_json / to_nice_yaml- Serialize a data structure for output into a config file or debug message
- regex_replace(pat, repl)- Regex-based string substitution inside a Jinja2 expression
- map('attribute', 'x')- Extract a field from each item in a list of dicts, e.g. group hosts by inventory_hostname
- selectattr / rejectattr- Filter a list of dicts by a boolean test on one of their attributes
- bool / int- Coerce string variables (often from extra-vars) into the correct type for comparisons
- combine(dict2)- Merge two dictionaries, useful for layering defaults with host-specific overrides
Use 'ansible-vault encrypt secrets.yml' to store passwords and API keys encrypted at rest in your repo, then reference them normally in playbooks — Ansible decrypts them at runtime with --ask-vault-pass or a vault password file.