Ansible Cheatsheet
Ansible is an open-source IT automation engine for configuration management, application deployment, and task orchestration. This cheatsheet covers ad-hoc commands, playbook writing, module usage, inventory management, variables, and debugging.
Ad-Hoc Commands
Ad-hoc commands execute a single task quickly using ansible -m -a "".
### Connectivity Test
``yaml
# Test connectivity of all hosts (ping module)
ansible all -m ping
`
### Execute Commands
`yaml
# Run a shell command on the webservers group
ansible webservers -m shell -a "uptime"
# Run a command module (no pipes/redirects)
ansible webservers -m command -a "whoami"
`
### File Operations
`yaml
# Copy a local file to remote hosts
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts owner=root group=root mode=0644"
# Manage file attributes (create/delete/permissions) ansible all -m file -a "path=/app/data state=directory mode=0755"
# Delete a file
ansible all -m file -a "path=/tmp/old.log state=absent"
`
### Package Management
`yaml
# Debian/Ubuntu install package
ansible all -m apt -a "name=nginx state=present" -b
# RHEL/CentOS install package
ansible all -m yum -a "name=httpd state=latest" -b
`
### Service Management
`yaml
# Start and enable a service
ansible all -m service -a "name=nginx state=started enabled=yes" -b
# Use systemd module
ansible all -m systemd -a "name=nginx state=restarted daemon_reload=yes" -b
`
Inventory Management
The inventory defines target hosts and groups in INI or YAML format.
### Basic Inventory (INI Format)
`yaml
# /etc/ansible/hosts
# [webservers]
# web1 ansible_host=192.168.1.10
# web2 ansible_host=192.168.1.11
#
# [dbservers]
# db1 ansible_host=192.168.1.20
#
# [all:vars]
# ansible_user=deploy
# ansible_port=22
# View inventory ansible-inventory --list
# Use a custom inventory file ansible all -i inventory.ini -m ping
# Limit targets to a single host
ansible-playbook site.yml --limit web1
`
### Dynamic Inventory
`yaml
# Use AWS EC2 dynamic inventory
ansible-inventory -i aws_ec2.yaml --graph
# List all hosts in inventory
ansible all -i aws_ec2.yaml --list-hosts
`
Modules
Ansible ships with thousands of built-in modules. Below are common examples.
### Template and Configuration
`yaml
# Render a Jinja2 template
- name: Configure nginx virtual host
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/sites-available/default
owner: root
group: root
mode: "0644"
notify: restart nginx
`
### Network and Downloads
`yaml
# Download a file
ansible all -m get_url -a "url=https://example.com/file.tar.gz dest=/tmp/file.tar.gz checksum=sha256:abc123"
# Extract an archive
ansible all -m unarchive -a "src=/tmp/file.tar.gz dest=/opt/app remote_src=yes creates=/opt/app/bin"
`
### Git Operations
`yaml
# Clone a Git repository
ansible all -m git -a "repo=https://github.com/example/app.git dest=/opt/app version=main force=yes"
`
### Docker Containers
`yaml
# Manage a Docker container
ansible all -m docker_container -a "name=myapp image=nginx:alpine state=started ports=80:80 restart_policy=always"
`
Playbook Writing
Playbooks are the heart of Ansible automation, written in YAML.
### Basic Playbook Structure
`yaml
---
- name: Deploy Web Application
hosts: webservers
become: yes
vars:
app_port: 8080
tasks:
- name: Ensure Nginx is installed
apt:
name: nginx
state: present
- name: Deploy configuration file template: src: app.conf.j2 dest: /etc/nginx/conf.d/app.conf notify: restart nginx
- name: Ensure service is running service: name: nginx state: started enabled: yes
handlers:
- name: restart nginx
service:
name: nginx
state: restarted
`
### Conditions and Loops
`yaml
# Conditional execution (when)
- name: Run only on Debian systems
apt:
name: python3
state: present
when: ansible_os_family == "Debian"
# Simple loop - name: Create multiple users user: name: "{{ item }}" state: present groups: sudo loop: - alice - bob - charlie
# Dictionary loop
- name: Configure multiple service ports
firewalld:
service: "{{ item.key }}"
port: "{{ item.value }}"
permanent: yes
state: enabled
loop: "{{ services | dict2items }}"
vars:
services:
http: 80
https: 443
`
### Includes and Imports
`yaml
# Include tasks from another file
- name: Include common setup tasks
include_tasks: tasks/common_setup.yml
# Use roles
- name: Apply nginx role
hosts: webservers
roles:
- role: nginx
nginx_port: 8080
- role: geerlingguy.security
`
Variables and Templates
### Variable Definition and Usage
`yaml
# Define variables in a playbook
vars:
domain: example.com
ssl_cert_path: /etc/ssl/certs/{{ domain }}.pem
# Interactive variable prompts
- name: Prompt for variables
hosts: all
vars_prompt:
- name: admin_password
prompt: "Enter admin password"
private: yes
confirm: yes
- name: deploy_version
prompt: "Deployment version"
default: "1.0.0"
`
### Registering Variables and Debugging
`yaml
# Register task output
- name: Check disk space
shell: df -h /
register: disk_output
# Debug output - name: Show disk information debug: msg: "Disk usage: {{ disk_output.stdout }}"
# Debug variables - name: Print all host variables debug: var: hostvars[inventory_hostname]
# Conditional based on registered variable
- name: Alert on low disk space
fail:
msg: "Disk usage exceeds 90%"
when: "'90%' in disk_output.stdout"
`
Advanced Features
### Tags
`yaml
# Tag tasks for selective execution
tasks:
- name: Install base packages
apt:
name: "{{ item }}"
loop:
- curl
- vim
- git
tags:
- packages
- base
- name: Configure firewall ufw: rule: allow port: "22,80,443" tags: - firewall - security
# Run specific tags # ansible-playbook site.yml --tags security
# Skip specific tags
# ansible-playbook site.yml --skip-tags firewall
`
### Vault (Encryption)
`yaml
# Encrypt sensitive files
# ansible-vault encrypt secrets.yml
# Use encrypted variables # vars_files: # - secrets.yml
# Decrypt during playbook run
# ansible-playbook site.yml --ask-vault-pass
`
### Common Playbook Options
`yaml
# Check mode (dry run, no changes)
# ansible-playbook site.yml --check
# Show diff of changes # ansible-playbook site.yml --diff
# Verbose output # ansible-playbook site.yml -vvv
# Specify SSH user # ansible-playbook site.yml -u deploy
# Specify private key # ansible-playbook site.yml --private-key ~/.ssh/deploy_key
# Serial execution (one host at a time) # ansible-playbook site.yml --forks 1
# Syntax check only # ansible-playbook site.yml --syntax-check ``
Ad-Hoc(10)
| Command | Level | ||
|---|---|---|---|
ansible all -m pingTest connectivity of all hosts | Basic | ansible all -m ping | |
ansible webservers -m command -a "whoami"Run a command on a host group (no pipes) | Basic | ansible webservers -m command -a "whoami" | |
ansible all -m shell -a "uptime"Execute a shell command on a host group | Basic | ansible all -m shell -a "uptime" | |
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts mode=0644"Copy a local file to remote hosts | Basic | ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts owner=root group=root mode=0644" | |
ansible all -m file -a "path=/app/data state=directory mode=0755"Create a directory with specific permissions | Basic | ansible all -m file -a "path=/app/data state=directory mode=0755" | |
ansible all -m file -a "path=/tmp/old.log state=absent"Delete a remote file | Basic | ansible all -m file -a "path=/tmp/old.log state=absent" | |
ansible all -m apt -a "name=nginx state=present" -bInstall a package with apt | Basic | ansible all -m apt -a "name=nginx state=present" -b | |
ansible all -m yum -a "name=httpd state=latest" -bInstall the latest package with yum | Basic | ansible all -m yum -a "name=httpd state=latest" -b | |
ansible all -m service -a "name=nginx state=started enabled=yes" -bStart and enable a service | Basic | ansible all -m service -a "name=nginx state=started enabled=yes" -b | |
ansible all -m systemd -a "name=nginx state=restarted daemon_reload=yes"Restart a service and reload systemd daemon | Intermediate | ansible all -m systemd -a "name=nginx state=restarted daemon_reload=yes" |
Inventory(3)
| Command | Level | ||
|---|---|---|---|
ansible-inventory --listList inventory contents in JSON format | Basic | ansible-inventory --list | |
ansible all -i inventory.ini -m pingUse a custom inventory file | Basic | ansible all -i inventory.ini -m ping | |
ansible-inventory -i aws_ec2.yaml --graphView dynamic inventory graph | Intermediate | ansible-inventory -i aws_ec2.yaml --graph |
Modules(5)
| Command | Level | ||
|---|---|---|---|
ansible all -m get_url -a "url=https://example.com/file.tar.gz dest=/tmp/file.tar.gz"Download a file from a URL to remote hosts | Intermediate | ansible all -m get_url -a "url=https://example.com/file.tar.gz dest=/tmp/file.tar.gz" | |
ansible all -m unarchive -a "src=/tmp/file.tar.gz dest=/opt/app remote_src=yes"Extract an archive on remote hosts | Intermediate | ansible all -m unarchive -a "src=/tmp/file.tar.gz dest=/opt/app remote_src=yes" | |
ansible all -m git -a "repo=https://github.com/example/app.git dest=/opt/app version=main"Clone a Git repository | Intermediate | ansible all -m git -a "repo=https://github.com/example/app.git dest=/opt/app version=main force=yes" | |
ansible all -m docker_container -a "name=myapp image=nginx:alpine state=started ports=80:80"Manage a Docker container | Expert | ansible all -m docker_container -a "name=myapp image=nginx:alpine state=started ports=80:80 restart_policy=always" | |
ansible.builtin.templateRender configuration files with Jinja2 templates | Intermediate | ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
mode: '0644' |
Playbook(11)
| Command | Level | ||
|---|---|---|---|
ansible-playbook site.ymlRun an Ansible playbook | Basic | ansible-playbook site.yml | |
ansible-playbook site.yml --check --diffRun playbook in check mode with diff output | Intermediate | ansible-playbook site.yml --check --diff | |
ansible-playbook site.yml --syntax-checkCheck playbook syntax without executing | Basic | ansible-playbook site.yml --syntax-check | |
when: ansible_os_family == "Debian"Conditional task execution | Intermediate | when: ansible_os_family == "Debian" | |
loopIterate over items in a loop | Intermediate | loop:
- alice
- bob | |
include_tasksInclude tasks from an external file | Intermediate | include_tasks: tasks/common_setup.yml | |
rolesApply Ansible roles | Expert | roles:
- role: nginx
nginx_port: 8080 | |
tagsTag tasks for selective execution | Intermediate | tags:
- packages
- base | |
ansible-playbook site.yml --tags securityRun only tasks with specific tags | Intermediate | ansible-playbook site.yml --tags security | |
ansible-playbook site.yml --limit web1Limit playbook execution to a single host | Intermediate | ansible-playbook site.yml --limit web1 | |
ansible-playbook site.yml --private-key ~/.ssh/deploy_keySpecify SSH private key for connection | Basic | ansible-playbook site.yml --private-key ~/.ssh/deploy_key |
Debugging(2)
| Command | Level | ||
|---|---|---|---|
ansible-playbook site.yml -vvvRun playbook in verbose mode (level 3) | Intermediate | ansible-playbook site.yml -vvv | |
debugPrint debug information | Basic | debug:
msg: "{{ disk_output.stdout }}" |
Variables(5)
| Command | Level | ||
|---|---|---|---|
registerRegister task output into a variable | Intermediate | register: disk_output | |
vars_promptInteractive variable prompts | Intermediate | vars_prompt:
- name: admin_password
prompt: "Enter password"
private: yes | |
ansible-vault encrypt secrets.ymlEncrypt sensitive files with Ansible Vault | Expert | ansible-vault encrypt secrets.yml | |
ansible-vault decrypt secrets.ymlDecrypt a Vault-encrypted file | Expert | ansible-vault decrypt secrets.yml | |
ansible-playbook site.yml --ask-vault-passRun playbook and prompt for Vault password | Expert | ansible-playbook site.yml --ask-vault-pass |