Ansible Cheatsheet


Basic Commands

  • Run ad-hoc command on all hosts
ansible all -m ping
  • Run command on specific group
ansible webservers -m command -a "uptime"
  • Run command as sudo
ansible all -m command -a "systemctl status nginx" --become
  • Run command with specific user
ansible all -m command -a "whoami" --become-user=nginx
  • Check Ansible version
ansible --version
  • List all hosts in inventory
ansible all --list-hosts

Inventory Management

  • Use custom inventory file
ansible all -i inventory.ini -m ping
  • Example static inventory file (inventory.ini)
[webservers]
web1.example.com
web2.example.com

[databases]
db1.example.com
db2.example.com

[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_rsa
  • Example dynamic inventory (YAML)
all:
  children:
    webservers:
      hosts:
        web1.example.com:
        web2.example.com:
    databases:
      hosts:
        db1.example.com:
  • View inventory structure
ansible-inventory --list
  • View specific group
ansible-inventory --list --yaml webservers

Playbooks

  • Run a playbook
ansible-playbook playbook.yml
  • Run playbook with specific inventory
ansible-playbook -i inventory.ini playbook.yml
  • Dry run (check mode)
ansible-playbook playbook.yml --check
  • Run with increased verbosity
ansible-playbook playbook.yml -v
# or -vv, -vvv for more detail
  • Run specific tags
ansible-playbook playbook.yml --tags "install,configure"
  • Skip specific tags
ansible-playbook playbook.yml --skip-tags "testing"
  • Example basic playbook
---
- name: Install and configure nginx
  hosts: webservers
  become: yes
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present
        update_cache: yes

    - name: Start nginx service
      systemd:
        name: nginx
        state: started
        enabled: yes

Common Modules

  • Package management (apt/yum)
ansible all -m apt -a "name=nginx state=present" --become
  • Service management
ansible all -m systemd -a "name=nginx state=started enabled=yes" --become
  • Copy files
ansible all -m copy -a "src=/local/file dest=/remote/file owner=root mode=644" --become
  • Template files
ansible all -m template -a "src=template.j2 dest=/etc/config.conf" --become
  • Create directories
ansible all -m file -a "path=/opt/myapp state=directory owner=root group=root mode=755" --become
  • Download files
ansible all -m get_url -a "url=https://example.com/file.tar.gz dest=/tmp/"
  • Execute shell commands
ansible all -m shell -a "echo $HOME"
  • Gather facts
ansible all -m setup

Variables and Facts

  • Use variables in playbook
---
- name: Use variables
  hosts: all
  vars:
    app_name: myapp
    app_version: 1.0
  tasks:
    - name: Create app directory
      file:
        path: "/opt/{{ app_name }}"
        state: directory
  • External variable files
ansible-playbook playbook.yml --extra-vars "@vars.yml"
  • Pass variables via command line
ansible-playbook playbook.yml --extra-vars "version=2.0 environment=production"
  • View all facts for host
ansible hostname -m setup
  • View specific facts
ansible hostname -m setup -a "filter=ansible_distribution*"

Roles

  • Create role structure
ansible-galaxy init myrole
  • Install role from Galaxy
ansible-galaxy install geerlingguy.nginx
  • Install roles from requirements file
ansible-galaxy install -r requirements.yml
  • Example requirements.yml
---
- name: geerlingguy.nginx
  version: 2.8.0
- src: https://github.com/username/repo.git
  name: custom-role
  • Use role in playbook
---
- name: Configure web servers
  hosts: webservers
  roles:
    - geerlingguy.nginx
    - { role: myapp, app_env: production }

Ansible Vault

  • Create encrypted file
ansible-vault create secrets.yml
  • Edit encrypted file
ansible-vault edit secrets.yml
  • View encrypted file
ansible-vault view secrets.yml
  • Encrypt existing file
ansible-vault encrypt vars.yml
  • Decrypt file
ansible-vault decrypt vars.yml
  • Change vault password
ansible-vault rekey secrets.yml
  • Run playbook with vault
ansible-playbook playbook.yml --ask-vault-pass
  • Use vault password file
ansible-playbook playbook.yml --vault-password-file .vault_pass

Conditionals and Loops

  • Conditional execution
- name: Install package on Ubuntu
  apt:
    name: nginx
    state: present
  when: ansible_distribution == "Ubuntu"
  • Loop over list
- name: Install multiple packages
  apt:
    name: "{{ item }}"
    state: present
  loop:
    - nginx
    - git
    - curl
  • Loop over dictionary
- name: Create users
  user:
    name: "{{ item.name }}"
    shell: "{{ item.shell }}"
  loop:
    - { name: 'user1', shell: '/bin/bash' }
    - { name: 'user2', shell: '/bin/zsh' }

Error Handling

  • Ignore errors
- name: This might fail
  command: /bin/false
  ignore_errors: yes
  • Handle failures
- name: Attempt something
  command: /might/fail
  register: result
  failed_when: result.rc != 0 and "expected error" not in result.stderr
  • Retry on failure
- name: Download file
  get_url:
    url: https://example.com/file.tar.gz
    dest: /tmp/file.tar.gz
  retries: 3
  delay: 5

Debugging and Testing

  • Debug variable values
- name: Show variable
  debug:
    var: ansible_hostname
  • Debug with message
- name: Show custom message
  debug:
    msg: "The hostname is {{ ansible_hostname }}"
  • Syntax check
ansible-playbook playbook.yml --syntax-check
  • List tasks in playbook
ansible-playbook playbook.yml --list-tasks
  • List hosts affected
ansible-playbook playbook.yml --list-hosts
  • Step through playbook
ansible-playbook playbook.yml --step

Configuration

  • View Ansible configuration
ansible-config view
  • List all config options
ansible-config list
  • Example ansible.cfg
[defaults]
inventory = ./inventory
remote_user = ubuntu
private_key_file = ~/.ssh/id_rsa
host_key_checking = False
retry_files_enabled = False

[privilege_escalation]
become = True
become_method = sudo
become_user = root

Useful Patterns

  • Run playbook on single host
ansible-playbook playbook.yml --limit "web1.example.com"
  • Run on subset of hosts
ansible-playbook playbook.yml --limit "webservers:&production"
  • Exclude hosts
ansible-playbook playbook.yml --limit "all:!databases"
  • Check if service is running
- name: Check if nginx is running
  command: systemctl is-active nginx
  register: nginx_status
  failed_when: false
  changed_when: false
  • Restart service only if config changed
- name: Copy nginx config
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
  notify: restart nginx

handlers:
  - name: restart nginx
    systemd:
      name: nginx
      state: restarted