---
title: "Ansible"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/ansible
---

0

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Ansible

Ansible cheatsheet covering playbooks, inventories, roles, tasks, variables, handlers, ad-hoc commands, modules, and configuration options.

10 Categories36 Sections72 ExamplesPublished: 28 Feb 2025Updated: 28 Feb 2026

[Markdown for AI(opens in a new tab)](/ansible/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Infrastructure as Code Mastery](/series/infrastructure-as-code-mastery)1/2

[NextChef](/cheatsheets/chef)

All posts in this series (2)

Cheatsheets2

1.  [AnsibleYou are here](/cheatsheets/ansible)
2.  [Chef](/cheatsheets/chef)

Ansible is an automation tool for configuration management, application deployment, and orchestration. This cheatsheet is a quick reference for common Ansible tasks, modules, and best practices.

[Getting Started](#category-gettingstarted)

-   [Installation & Setup](#section-installation)
-   [Ansible Configuration File](#section-configfile)
-   [First Playbook Run](#section-firstrun)
-   [Test Host Connectivity](#section-connectivity)

[Inventory Management](#category-inventory)

-   [Inventory Formats](#section-invertoryformat)
-   [Host Patterns](#section-hostpatterns)
-   [Dynamic Inventory](#section-dynamicinventory)
-   [Host Variables & Priorities](#section-hostpriorities)

[Ad-Hoc Commands](#category-adhoc)

-   [Basic Syntax](#section-basicsyntax)
-   [Common Ad-Hoc Modules](#section-commonmodules)
-   [Parallelism & Forks](#section-forks)

[Playbooks](#category-playbooks)

-   [Playbook Structure](#section-structure)
-   [Playbook Execution](#section-execution)
-   [Conditionals](#section-conditionals)

[Tasks & Handlers](#category-taskshandlers)

-   [Task Structure](#section-taskstructure)
-   [Handlers](#section-handlers)
-   [Loops](#section-loops)

[Variables & Facts](#category-variables)

-   [Variable Definition](#section-vardefine)
-   [Gathering Facts](#section-facts)
-   [Variable Precedence](#section-varprecedence)
-   [Variable Templating](#section-vartemplating)

[Roles](#category-roles)

-   [Role Structure](#section-rolestructure)
-   [Role Options & Includes](#section-roleoptions)
-   [Role Dependencies](#section-dependencies)

[Modules](#category-modules)

-   [System Modules](#section-systemmodules)
-   [Package Management](#section-packagemodules)
-   [Command Execution](#section-commandmodules)
-   [Web & Net Modules](#section-webmodules)

[Advanced Features](#category-advanced)

-   [Blocks & Error Handling](#section-blocks)
-   [Asynchronous Execution](#section-asynctasks)
-   [Advanced Variable Usage](#section-advancedvars)
-   [Plugins & Extensions](#section-plugins)

[Vault & Security](#category-vault)

-   [Vault Basics](#section-vaultbasics)
-   [Using Vault in Playbooks](#section-vaultusage)
-   [Encrypt Individual Files](#section-vaultencrypt)
-   [Vault Best Practices](#section-vaultbest)

No commands found

Try adjusting your search term

## Getting Started

### Installation & Setup

Install Ansible and configure basic settings

#### Accessibility

Beginner

#### Keywords

installsetupconfigrequirements

#### Install Ansible on Ubuntu

Code

Terminal window

```
sudo apt updatesudo apt install -y ansible
```

#### Install Ansible via pip

Code

Terminal window

```
pip install ansiblepip install ansible==2.10.7
```

#### Verify Ansible Installation

Displays installed Ansible version and configuration details

Code

Terminal window

```
ansible --version
```

Execution

Terminal window

```
ansible 2.10.7  config file = /etc/ansible/ansible.cfg  configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']  ansible python module location = /usr/lib/python3/dist-packages/ansible  executable location = /usr/bin/ansible  python version = 3.10.12
```

-   Version should be 2.9+
-   Python 3.6+ required

### Ansible Configuration File

Main configuration file setup at ansible.cfg

#### Accessibility

Beginner

#### Keywords

configansible.cfgsettingsoptions

#### Create Basic ansible.cfg

Code

```
1[defaults]2inventory = ./hosts3remote_user = ubuntu4private_key_file = ~/.ssh/id_rsa5host_key_checking = False6gather_facts = True
```

#### Configure Parallel Execution

forks increases parallelism for faster execution

Code

```
1[defaults]2forks = 103timeout = 304retries = 3
```

-   Default forks value is 5
-   Higher forks = more parallelism = higher memory usage

### First Playbook Run

Execute your first Ansible playbook

#### Accessibility

Beginner

#### Keywords

playbookfirsthellotestrun

#### Simple Hello World Playbook

Basic playbook that prints a debug message

Code

```
1---2- name: Hello World3  hosts: all4  tasks:5    - name: Print Hello6      debug:7        msg: "Hello from Ansible"
```

Execution

Terminal window

```
PLAY [Hello World] *****TASK [Print Hello] *****ok: [localhost] => {    "msg": "Hello from Ansible"}PLAY RECAP *****localhost : ok=1 changed=0 failed=0
```

-   Playbooks must be valid YAML
-   \[object Object\]

### Test Host Connectivity

Verify connectivity to managed hosts

#### Accessibility

Beginner

#### Keywords

pingconnectivitytesthostsnetwork

#### Ping All Hosts

Tests connectivity to all hosts without running tasks

Code

Terminal window

```
ansible all -i hosts -m ping
```

Execution

Terminal window

```
webserver01 | SUCCESS => {    "ansible_facts": {        "discovered_interpreter_python": "/usr/bin/python3"    },    "changed": false,    "ping": "pong"}database01 | SUCCESS => {    "ping": "pong"}
```

-   ping module requires Python on remote
-   SUCCESS indicates host is reachable

## Inventory Management

### Inventory Formats

Different ways to define managed hosts

#### Accessibility

Beginner

#### Keywords

inventoryhostsiniyamlformat

#### INI Format Inventory

INI format with groups and variables

Code

```
1[webservers]2web1 ansible_host=192.168.1.103web2 ansible_host=192.168.1.114
5[databases]6db1 ansible_host=192.168.1.207db2 ansible_host=192.168.1.218
9[all:vars]10ansible_user=ubuntu11ansible_ssh_private_key_file=~/.ssh/id_rsa
```

-   Groups defined with \[groupname\]
-   \[all:vars\] applies to all hosts

#### YAML Format Inventory

YAML format for complex hierarchies

Code

```
1all:2  children:3    webservers:4      hosts:5        web1:6          ansible_host: 192.168.1.107        web2:8          ansible_host: 192.168.1.119    databases:10      hosts:11        db1:12          ansible_host: 192.168.1.2013  vars:14    ansible_user: ubuntu
```

-   Better for nested groups
-   More readable for complex inventories

### Host Patterns

Select specific hosts or groups

#### Accessibility

Beginner

#### Keywords

patternselectionfiltergrouphost

#### Target Specific Groups

webservers targets group, !web2 excludes host

Code

Terminal window

```
ansible webservers -i hosts -m pingansible databases -i hosts -m pingansible 'webservers:!web2' -i hosts -m ping
```

Execution

Terminal window

```
web1 | SUCCESS => {"ping": "pong"}web2 | SUCCESS => {"ping": "pong"}
```

-   webservers selects entire group
-   negates selection

#### Wildcard and Range Patterns

Wildcards match patterns, \[1:2\] matches range

Code

Terminal window

```
ansible 'web*' -i hosts -m pingansible 'db[1:2]' -i hosts -m pingansible 'webservers[0]' -i hosts -m ping
```

-   \* matches any characters
-   \[1:2\] includes indexes 1 and 2

### Dynamic Inventory

Generate inventory from external sources

#### Accessibility

Intermediate

#### Keywords

dynamicinventoryscriptplugincloud

#### EC2 Dynamic Inventory

AWS EC2 plugin pulls instances from AWS

Code

```
1plugin: aws_ec22regions:3  - us-east-14filters:5  tag:Environment: production6keyed_groups:7  - key: placement.region_name8    prefix: aws_region
```

-   Requires boto3 library
-   Cache results for performance

#### Custom Inventory Script

Custom script outputs JSON inventory format

Code

```
#!/bin/bashcat << EOF{  "webservers": {    "hosts": ["web1", "web2"]  }}EOF
```

-   Script must be executable
-   Output must be valid JSON

### Host Variables & Priorities

Set variables at different levels

#### Accessibility

Intermediate

#### Keywords

variableshostgrouppriorityprecedence

#### Host-Level Variables

Variables specific to individual hosts

Code

```
1all:2  children:3    webservers:4      hosts:5        web1:6          ansible_host: 192.168.1.107          http_port: 808          server_role: primary
```

-   Host variables override group variables
-   Highest precedence level

#### Group Variables File

Load variables from files by host/group name

Code

Terminal window

```
group_vars/webservers.ymlgroup_vars/webservers/main.ymlhost_vars/web1.yml
```

-   group\_vars/groupname.yml for entire group
-   host\_vars/hostname.yml for single host

## Ad-Hoc Commands

### Basic Syntax

Run single tasks without playbook

#### Accessibility

Beginner

#### Keywords

adhoccommandmoduleexecuteone-time

#### Run Adhoc Command

Execute shell command on all hosts

Code

Terminal window

```
ansible all -i hosts -m shell -a "uptime"
```

Execution

Terminal window

```
web1 | CHANGED | rc=0 >> 10:45:23 up 5 days,  3:21,  2 users,  load average: 0.05, 0.10, 0.08web2 | CHANGED | rc=0 >> 10:45:24 up 3 days,  1:15,  1 user,  load average: 0.02, 0.06, 0.05
```

-   \-m specifies module
-   \-a passes arguments

#### Use copy Module

Copy file from control node to remote

Code

Terminal window

```
ansible webservers -i hosts -m copy -a "src=/etc/hosts dest=/tmp/hosts"
```

Execution

Terminal window

```
web1 | CHANGED => {    "changed": true,    "checksum": "5d41402abc4b2a76b9719d911017c592",    "dest": "/tmp/hosts",    "gid": 0,    "mode": "0644",    "owner": "root",    "size": 158,    "src": "/tmp/ansible.87a8vz/hosts",    "state": "file"}
```

-   src path on control node
-   dest path on remote

### Common Ad-Hoc Modules

Frequently used modules for ad-hoc tasks

#### Accessibility

Beginner

#### Keywords

modulecommandshellcopyfileservice

#### Package Management

Install nginx package

Code

Terminal window

```
ansible webservers -i hosts -m apt -a "name=nginx state=present"
```

Execution

Terminal window

```
web1 | CHANGED => {    "changed": true,    "stderr": "",    "stdout": "Reading package lists..."}
```

-   apt for Debian/Ubuntu
-   yum for Red Hat/CentOS

#### Service Management

Start nginx service and enable on boot

Code

Terminal window

```
ansible webservers -i hosts -m service -a "name=nginx state=started enabled=yes"
```

Execution

Terminal window

```
web1 | CHANGED => {    "changed": true,    "enabled": true,    "name": "nginx",    "state": "started"}
```

-   \[object Object\]
-   enabled=yes enables service on boot

#### File Permissions

Set file permissions and ownership

Code

Terminal window

```
ansible all -i hosts -m file -a "path=/tmp/test.txt mode=0644 owner=root"
```

Execution

Terminal window

```
web1 | CHANGED => {    "changed": true,    "mode": "0644",    "owner": "root",    "path": "/tmp/test.txt"}
```

-   mode in octal format
-   owner and group can be specified

### Parallelism & Forks

Control how many hosts execute simultaneously

#### Accessibility

Intermediate

#### Keywords

forkparallellimitbatchspeed

#### Limit Concurrent Execution

Execute on 2 hosts at a time instead of default

Code

Terminal window

```
ansible all -i hosts -m ping -f 2
```

-   \-f or --forks sets parallelism
-   Lower for safety, higher for speed

#### Serial Execution

Execute one at a time (serial)

Code

Terminal window

```
ansible all -i hosts -m shell -a "systemctl restart app" -f 1
```

-   Useful for rolling restarts
-   Prevents service downtime

## Playbooks

### Playbook Structure

Create and organize playbooks

#### Accessibility

Beginner

#### Keywords

playbookstructureyamltaskshosts

#### Basic Playbook Structure

Complete playbook with all major sections

Code

```
1---2- name: Deploy Web Application3  hosts: webservers4  become: yes5  vars:6    app_port: 80807    app_user: www-data8  tasks:9    - name: Install dependencies10      apt:11        name: python3-pip12        state: present13    - name: Start application14      command: /opt/app/start.sh
```

-   \--- indicates YAML document start
-   \[object Object\]
-   \[object Object\]

#### Multiple Plays in Single Playbook

Multiple plays execute sequentially

Code

```
1---2- name: Configure Databases3  hosts: databases4  tasks:5    - debug: msg="Setting up database"6
7- name: Configure Web Servers8  hosts: webservers9  tasks:10    - debug: msg="Setting up web server"
```

-   Each play is independent
-   Plays execute in order

### Playbook Execution

Run playbooks with various options

#### Accessibility

Beginner

#### Keywords

runexecutesyntaxchecktagsverbose

#### Run Basic Playbook

Execute playbook against specified inventory

Code

Terminal window

```
ansible-playbook playbook.yml -i hosts
```

Execution

Terminal window

```
PLAY [Deploy Web Application] *****TASK [Install dependencies] *****ok: [web1]ok: [web2]TASK [Start application] *****changed: [web1]changed: [web2]PLAY RECAP *****web1 : ok=2 changed=1 failed=0web2 : ok=2 changed=1 failed=0
```

-   ok = task already in desired state
-   changed = task made changes

#### Check Mode (Dry Run)

Preview changes without executing

Code

Terminal window

```
ansible-playbook playbook.yml -i hosts --check
```

-   Shows what would change
-   Useful before production runs

#### Run with Extra Variables

Pass variables from command line

Code

Terminal window

```
ansible-playbook playbook.yml -i hosts -e "env=production app_version=2.0"
```

-   \-e or --extra-vars for variables
-   Overrides defaults in playbook

#### Verbose Output

Show detailed execution information

Code

Terminal window

```
ansible-playbook playbook.yml -i hosts -vvv
```

-   \-v = info, -vv = debug, -vvv = extra debug

### Conditionals

Execute tasks based on conditions

#### Accessibility

Intermediate

#### Keywords

whenconditionalifconditiontest

#### Simple When Condition

Skip task if condition false

Code

```
1- name: Install nginx if not exists2  apt:3    name: nginx4    state: present5  when: ansible_distribution == "Ubuntu"
```

Execution

Terminal window

```
TASK [Install nginx if not exists] *****skipped: [web1] => (item=centos)ok: [web2] => (item=ubuntu)
```

-   Conditions use when keyword
-   Access facts with ansible\_variablename

#### Multiple Conditions

All conditions must be true (AND logic)

Code

```
1- name: Restart service2  service:3    name: nginx4    state: restarted5  when:6    - ansible_os_family == "Debian"7    - ansible_distribution_version >= "20.04"
```

-   List format uses AND logic
-   \[object Object\]

## Tasks & Handlers

### Task Structure

Define and organize tasks

#### Accessibility

Beginner

#### Keywords

tasknameregisterdebugaction

#### Basic Task Definition

Task with module, arguments, and tags

Code

```
1- name: Install web server2  apt:3    name: nginx4    state: present5  become: yes6  tags:7    - webserver8    - packages
```

-   \[object Object\]
-   \[object Object\]

#### Register Task Output

Save task output in variable for later use

Code

```
1- name: Get service status2  command: systemctl status nginx3  register: nginx_status4  changed_when: false5
6- name: Display status7  debug:8    msg: "{{ nginx_status.stdout }}"
```

-   register stores full result
-   Access with variable name

### Handlers

Run tasks on change events

#### Accessibility

Intermediate

#### Keywords

handlernotifychangedeventrestart

#### Basic Handler

Handler executes if task notifies it

Code

```
1- name: Deploy application2  hosts: webservers3  tasks:4    - name: Copy app config5      copy:6        src: app.conf7        dest: /etc/app/app.conf8      notify: restart app9  handlers:10    - name: restart app11      service:12        name: app13        state: restarted
```

-   Handlers only run if task changed
-   Run at end of play by default

#### Multiple Handlers

Single task can notify multiple handlers

Code

```
1tasks:2  - name: Update config3    template:4      src: nginx.conf.j25      dest: /etc/nginx/nginx.conf6    notify:7      - reload nginx8      - log config change9handlers:10  - name: reload nginx11    service:12      name: nginx13      state: reloaded14  - name: log config change15    command: logger "nginx config updated"
```

-   Handlers run in defined order
-   Duplicate handler calls only run once

### Loops

Repeat tasks with different variables

#### Accessibility

Intermediate

#### Keywords

loopwith\_itemsiteraterepeatforeach

#### Loop Over List

Item variable changes per loop iteration

Code

```
1- name: Install multiple packages2  apt:3    name: "{{ item }}"4    state: present5  loop:6    - nginx7    - php-fpm8    - mysql-client
```

Execution

Terminal window

```
TASK [Install multiple packages] *****ok: [web1] => (item=nginx)ok: [web1] => (item=php-fpm)ok: [web1] => (item=mysql-client)
```

-   \[object Object\]
-   item is implicit variable name

#### Loop Over Dict

Loop over dictionary structures

Code

```
1- name: Create users2  user:3    name: "{{ item.name }}"4    uid: "{{ item.uid }}"5    state: present6  loop:7    - { name: 'alice', uid: 1001 }8    - { name: 'bob', uid: 1002 }
```

-   Access dict items with dot notation
-   Useful for complex configurations

## Variables & Facts

### Variable Definition

Define and use variables

#### Accessibility

Beginner

#### Keywords

variablevardefinesetvalue

#### Play-Level Variables

Define variables at play scope

Code

```
1- name: My playbook2  hosts: all3  vars:4    db_host: localhost5    db_port: 33066    db_name: myapp7    env: production8  tasks:9    - name: Connect to database10      debug:11        msg: "Connecting to {{ db_host }}:{{ db_port }}"
```

-   Accessible in all tasks
-   {{ }} for variable substitution

#### Task-Level Variables

Variables local to specific task

Code

```
1- name: Configure service2  service:3    name: nginx4    state: started5  vars:6    nginx_user: www-data7    nginx_workers: 4
```

-   Only available in this task's context

### Gathering Facts

Collect system information from hosts

#### Accessibility

Beginner

#### Keywords

factsgatherdiscoverysysteminfo

#### Auto-Gather Facts

Facts gathered by default unless disabled

Code

```
1- name: Display fact2  hosts: all3  tasks:4    - name: Show OS5      debug:6        msg: "OS: {{ ansible_os_family }}, Memory: {{ ansible_memtotal_mb }}"
```

Execution

Terminal window

```
TASK [Show OS] *****ok: [web1] => {    "msg": "OS: Debian, Memory: 4096"}
```

-   ansible\_\* variables are facts
-   \[object Object\]

#### Custom Facts

Define custom facts in JSON files

Code

Terminal window

```
/etc/ansible/facts.d/custom.fact{  "app_version": "2.1.0",  "deployment_date": "2026-01-15"}
```

-   Store in /etc/ansible/facts.d/
-   Extension must be .fact

### Variable Precedence

Order of variable resolution

#### Accessibility

Intermediate

#### Keywords

precedencepriorityoverrideorder

#### Precedence Levels

Variables override based on source location

Code

```
1# Lowest to highest precedence:2# 1. defaults/main.yml in role3# 2. group_vars/all4# 3. group_vars/groupname5# 4. host_vars/hostname6# 5. vars in playbook7# 6. vars_files8# 7. task vars9# 8. -e extra vars (highest)
```

-   Command line (-e) always wins
-   Host vars override group vars

#### Override with Extra Vars

Extra vars override all others

Code

Terminal window

```
ansible-playbook playbook.yml -e "db_host=newhost db_port=5432"
```

-   \-e highest precedence
-   Useful for overriding defaults

### Variable Templating

Template and manipulate variable values

#### Accessibility

Intermediate

#### Keywords

templatejinja2filtertransformformat

#### Jinja2 Filters

Transform variables with filters

Code

```
1- name: Use filters2  debug:3    msg: |4      Uppercase: {{ service_name | upper }}5      Lowercase: {{ domain | lower }}6      Default: {{ undefined_var | default('localhost') }}7      List join: {{ servers | join(',') }}
```

Execution

Terminal window

```
TASK [Use filters] *****ok: [localhost] => {    "msg": "Uppercase: NGINX\nLowercase: example.com\nDefault: localhost\nList join: web1,web2,web3"}
```

-   | for multiline strings
-   | filters modify variable values

## Roles

### Role Structure

Organize code with roles

#### Accessibility

Intermediate

#### Keywords

rolestructuredirectoryreusableorganize

#### Role Directory Structure

Standard role directory structure

Code

Terminal window

```
roles/webserver/├── tasks/│   └── main.yml├── handlers/│   └── main.yml├── vars/│   └── main.yml├── defaults/│   └── main.yml├── files/├── templates/└── meta/    └── main.yml
```

-   tasks/ contains main task execution
-   defaults/ provides variable defaults

#### Role Definition

Define tasks in role

Code

roles/webserver/tasks/main.yml

```
1---2- name: Install web server3  apt:4    name: nginx5    state: present6  become: yes7
8- name: Copy config9  template:10    src: nginx.conf.j211    dest: /etc/nginx/nginx.conf12  notify: restart nginx
```

-   Include handler definitions
-   Keep role single-purpose

### Role Options & Includes

Include and configure roles

#### Accessibility

Intermediate

#### Keywords

includeimportrolevarsconfig

#### Include Role in Playbook

Include multiple roles

Code

```
1- name: Deploy web application2  hosts: webservers3  roles:4    - webserver5    - php6    - mysql
```

-   Roles execute in order
-   Most common role usage

#### Role with Variables

Pass variables to roles

Code

```
1- name: Deploy web application2  hosts: webservers3  roles:4    - role: webserver5      vars:6        nginx_port: 80807        nginx_workers: 88    - role: php9      when: "'php' in group_names"
```

-   Vars override role defaults
-   when can conditionally include roles

### Role Dependencies

Manage role dependencies

#### Accessibility

Intermediate

#### Keywords

dependencydependrequiremetainclude

#### Declare Dependencies

Specify required roles

Code

roles/php/meta/main.yml

```
1---2dependencies:3  - role: webserver4  - role: database5    vars:6      db_type: mysql
```

-   Dependencies execute first
-   Can pass variables to dependencies

## Modules

### System Modules

System administration modules

#### Accessibility

Beginner

#### Keywords

systempackageservicefileusergroup

#### User Management

Create system user with specified properties

Code

```
1- name: Create user2  user:3    name: appuser4    uid: 20005    home: /opt/app6    shell: /bin/bash7    state: present
```

Execution

Terminal window

```
ok: [web1] => {    "changed": false,    "comment": "",    "home": "/opt/app",    "name": "appuser",    "shell": "/bin/bash",    "uid": 2000}
```

-   \[object Object\]
-   uid specifies numeric user id

#### File Management

Create directory with permissions

Code

```
1- name: Create directory2  file:3    path: /opt/app/data4    state: directory5    mode: '0755'6    owner: appuser7    recurse: yes
```

Execution

Terminal window

```
changed: [web1] => {    "changed": true,    "mode": "0755",    "owner": "appuser",    "path": "/opt/app/data",    "state": "directory"}
```

-   \[object Object\]
-   \[object Object\]

### Package Management

Install and manage packages

#### Accessibility

Beginner

#### Keywords

packageaptyumpipinstall

#### APT Package Manager

Install multiple packages with cache update

Code

```
1- name: Install packages2  apt:3    name:4      - curl5      - wget6      - git7    state: present8    update_cache: yes
```

-   update\_cache updates apt database
-   \[object Object\]

#### PIP Package Manager

Install Python packages in virtualenv

Code

```
1- name: Install Python packages2  pip:3    name:4      - django==3.25      - requests>=2.256    virtualenv: /opt/app/venv
```

-   virtualenv creates/uses virtualenv
-   Version pinning with == or >=

### Command Execution

Execute commands on remote hosts

#### Accessibility

Intermediate

#### Keywords

commandshellscriptraw

#### Command Module (Preferred)

Execute command without shell processing

Code

```
1- name: Get nginx version2  command: nginx -v3  register: nginx_version4  changed_when: false
```

Execution

Terminal window

```
ok: [web1] => {    "cmd": ["nginx", "-v"],    "rc": 0,    "stderr": "nginx version: nginx/1.18.0",    "stdout": ""}
```

-   No shell expansion (\*, |, &)
-   More predictable

#### Shell Module

Execute with shell processing

Code

```
1- name: Check if file exists2  shell: |3    if [ -f /opt/app/config.yml ]; then4      echo "exists"5    else6      echo "missing"7    fi8  register: config_check
```

-   Supports pipes, redirects
-   Less secure, use with care

### Web & Net Modules

HTTP and network operations

#### Accessibility

Intermediate

#### Keywords

uriget\_urlurldownloadhttp

#### HTTP Request

Make HTTP request and validate response

Code

```
1- name: Health check2  uri:3    url: http://localhost:8080/health4    method: GET5    status_code: 2006  register: health_check
```

Execution

Terminal window

```
ok: [web1] => {    "changed": false,    "content": "{\"status\":\"ok\"}",    "status": 200}
```

-   status\_code validates response
-   body can parse JSON response

## Advanced Features

### Blocks & Error Handling

Group tasks and handle errors

#### Accessibility

Intermediate

#### Keywords

blockrescuealwayserrorexception

#### Block with Error Handling

Block groups tasks with error handling

Code

```
1- name: Database operations2  block:3    - name: Connect to database4      debug: msg="Connecting"5    - name: Run migrations6      command: /opt/app/migrations.sh7  rescue:8    - name: Rollback on error9      command: /opt/app/rollback.sh10  always:11    - name: Cleanup12      file:13        path: /tmp/app.lock14        state: absent
```

-   \[object Object\]
-   \[object Object\]
-   \[object Object\]

#### Validate Task Results

Control when task is marked failed/changed

Code

```
1- name: Run test2  shell: npm test3  failed_when: "npm_test.rc != 0"4  changed_when: false5  register: npm_test
```

-   failed\_when overrides failure detection
-   changed\_when overrides change detection

### Asynchronous Execution

Run long-running tasks in background

#### Accessibility

Intermediate

#### Keywords

asyncpollbackgroundlong-runningwait

#### Async with Polling

Run 1-hour task, check every 10 seconds

Code

```
1- name: Long running task2  shell: /opt/app/long-job.sh3  async: 36004  poll: 105  register: long_job
```

Execution

Terminal window

```
ASYNC OK on web1 (job_id=123456789.12345)
```

-   \[object Object\]
-   \[object Object\]

#### Fire and Forget

Start task and don't wait for completion

Code

```
1- name: Start background service2  shell: /opt/app/service.sh3  async: 04  poll: 0
```

-   async: 0 and poll: 0 for fire-and-forget

### Advanced Variable Usage

Complex variable patterns

#### Accessibility

Advanced

#### Keywords

variablecomplexnesteddictlisthostvars

#### Access Host Variables

Access variables from other hosts

Code

```
1- name: Reference another host2  debug:3    msg: "Database host: {{ hostvars['db1']['ansible_default_ipv4']['address'] }}"
```

-   hostvars dict contains all host info
-   Useful in multi-host plays

#### Nested Variable Access

Access deeply nested structures

Code

```
1vars:2  services:3    web:4      port: 80805      workers: 46    db:7      port: 54328      replicas: 39tasks:10  - debug: msg="Web port {{ services.web.port }}"
```

-   Dot notation for nested access
-   Bracket notation also works

### Plugins & Extensions

Extend Ansible functionality

#### Accessibility

Advanced

#### Keywords

pluginfilterlookupconnectioncallback

#### Custom Filters

Apply custom filter plugins

Code

```
1- name: Use custom filter2  debug:3    msg: "{{ 'hello' | custom_uppercase }}"
```

-   Place filters in filter\_plugins/
-   Extend Jinja2 capabilities

#### Lookup Plugins

Use lookup plugins for dynamic data

Code

```
1- name: Read file content2  set_fact:3    file_content: "{{ lookup('file', '/etc/config.yml') }}"4
5- name: Get environment variable6  debug:7    msg: "{{ lookup('env', 'HOME') }}"
```

-   file, env, pipe lookups common
-   Results available mid-playbook

## Vault & Security

### Vault Basics

Encrypt sensitive data

#### Accessibility

Intermediate

#### Keywords

vaultencryptsecretpasswordsecurity

#### Create Vault File

Create encrypted YAML file

Code

Terminal window

```
ansible-vault create secrets.yml# Enter password, then edit:# db_password: "secret123"# api_key: "abc123xyz"
```

Execution

Terminal window

```
New Vault password:Confirm New Vault password:
```

-   Creates .yml with encrypted content
-   Prompts for password

#### View Vault Content

Decrypt and display vault file

Code

Terminal window

```
ansible-vault view secrets.yml# Password prompt
```

-   Requires vault password
-   Doesn't save decrypted content

#### Edit Vault File

Edit encrypted vault file safely

Code

Terminal window

```
ansible-vault edit secrets.yml
```

-   Opens in editor
-   Re-encrypts on save

### Using Vault in Playbooks

Reference vault variables in playbooks

#### Accessibility

Intermediate

#### Keywords

vaultincludevarsplaytask

#### Include Vault Variables

Load vault variables in playbook

Code

```
1- name: Deploy app2  hosts: webservers3  vars_files:4    - secrets.yml5  tasks:6    - name: Configure database7      template:8        src: db.conf.j29        dest: /etc/app/db.conf10      vars:11        db_password: "{{ vault_db_password }}"
```

-   \[object Object\]
-   Automatic decryption on run

#### Run Playbook with Vault

Run playbook requiring vault password

Code

Terminal window

```
ansible-playbook playbook.yml -i hosts --ask-vault-pass
```

Execution

Terminal window

```
Vault password:PLAY [Deploy app] *****TASK [Configure database] *****ok: [web1]
```

-   \--ask-vault-pass prompts for password
-   \--vault-password-file for automation

### Encrypt Individual Files

Encrypt specific files or variables

#### Accessibility

Advanced

#### Keywords

encryptstringfileinlineprotect

#### Encrypt Single Variable

Encrypt individual secret for playbook

Code

Terminal window

```
ansible-vault encrypt_string --ask-vault-pass 'mypassword'
```

Execution

Terminal window

```
Reading plaintext input from stdin.New Vault password:Confirm New Vault password:!vault |  $ANSIBLE_VAULT;1.1;AES256  66386...
```

-   Generates encrypted string
-   Paste into playbook vars

#### Encrypt Specific Files

Encrypt individual variable files

Code

Terminal window

```
ansible-vault encrypt host_vars/prod.yml
```

-   Encrypts existing file in place

### Vault Best Practices

Security practices with vault

#### Accessibility

Intermediate

#### Best Practices

-   Rotate vault passwords regularly
-   Never commit .vault\_pass or passwords to git
-   Use --check before running production playbooks
-   Implement version control for playbooks
-   Document role dependencies
-   Use meaningful task names
-   Avoid hardcoding values
-   Test in development environment first
-   Use vault for all sensitive data
-   Limit who can decrypt vault files

#### Common Errors

-   **Forgetting the vault password prevents decryption.:** Keep a backup in a password manager
-   **Committing .vault\_pass exposes all secrets.:** Check .gitignore
-   **Mixing encrypted and plain text in the same file fails.:** Use separate vault files
-   **Skipping --check before a production run.:** Always check first

#### Keywords

vaultsecuritypracticepasswordprotect

[Learn more](https://docs.ansible.com/ansible/latest/user_guide/vault.html)

#### Password File Not in Repo

Store vault password file locally, not in git

Code

Terminal window

```
.gitignore:.vault_pass
Run playbook:ansible-playbook playbook.yml --vault-password-file ~/.vault_pass
```

-   Keep .vault\_pass outside repository
-   Use --vault-password-file for automation

#### Different Vaults for Environments

Separate encrypted files per environment

Code

Terminal window

```
group_vars/prod/secrets.yml (encrypted)group_vars/dev/secrets.yml (encrypted)group_vars/staging/secrets.yml (encrypted)
```

-   Different passwords per environment
-   Keeps secrets isolated between environments

Was this useful?

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Ansible&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible&title=Ansible&summary=Ansible%20cheatsheet%20covering%20playbooks%2C%20inventories%2C%20roles%2C%20tasks%2C%20variables%2C%20handlers%2C%20ad-hoc%20commands%2C%20modules%2C%20and%20configuration%20options.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Ansible%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible&text=Ansible "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible&title=Ansible "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible&t=Ansible "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible&media=&description=Ansible%20cheatsheet%20covering%20playbooks%2C%20inventories%2C%20roles%2C%20tasks%2C%20variables%2C%20handlers%2C%20ad-hoc%20commands%2C%20modules%2C%20and%20configuration%20options. "Share on Pinterest")[Email](<mailto:?subject=Ansible&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fansible>)

## Comments

## You might also enjoy

More posts on similar topics

## [Chef](/cheatsheets/chef)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Chef is an Infrastructure as Code platform for automating infrastructure configuration, deployment, and management. This cheatsheet covers Chef concepts, commands, patterns, and best practices for man

[read more](/cheatsheets/chef)

## [SSH](/cheatsheets/ssh)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

export const components = { h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', p: 'p', a: 'a', ul: 'ul', ol: 'ol', li: 'li', code: 'code', pre: 'pre', strong: 'str

[read more](/cheatsheets/ssh)

## [Docker Compose](/cheatsheets/docker-compose)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file to configure application services, networks, and volumes. This cheatsheet provides a quick re

[read more](/cheatsheets/docker-compose)

## [Dockerfile](/cheatsheets/dockerfile)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

This cheat sheet covers the core Dockerfile instructions, best practices, and common pitfalls for building small, secure Docker images. Each section pairs a Dockerfile snippet with the build output it

[read more](/cheatsheets/dockerfile)

## [PostgreSQL](/cheatsheets/postgresql)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

PostgreSQL reference guide covering psql commands, database creation, tables, queries, functions, joins, transactions, indexes, and advanced SQL operations.

[read more](/cheatsheets/postgresql)

## [Redis](/cheatsheets/redis)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Redis reference guide covering commands, data types, keys, strings, lists, sets, hashes, sorted sets, transactions, pub/sub, and caching strategies.

[read more](/cheatsheets/redis)

6 related posts
