You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Let's create the largest and most comprehensive cheat sheet for Ansible. If you have a tip or trick that you think should be included, please contribute.
Sponsors
❤️ The ansible Workshop: Hands-On Learning For Rapid Mastery
In "The Ansible Workshop," you will deep dive into the world of Ansible, the amazing automation tool that converts complex IT tasks into a set of easy, simple-to-repeat steps. This guide is your roadmap to mastering Ansible, whether you are a novice just starting to use Ansible or an intermediate user who has already used Ansible and is looking for additional information and tricks to enhance your skills.
DevOpsLinks - The Ultimate DevOps Newsletter. Curated DevOps news, tutorials, tools, jobs, podcasts, and more. Delivered to your inbox every week.
🛍️ ByteVibe: Show off your love for all things TECH
If you're seeking a cozy sweatshirt to wear during your extended coding sessions or a mug to exhibit your passion for programming, you can find it all here
💌 Sponsorship
If you would like to sponsor this project, please contact me at aymen at faun dot dev.
Call for Contributions
Let's create the largest and most comprehensive list of Ansible tools and resources. If you have a tool or resource that you think should be included, please contribute.
# Ubuntu/Debian
sudo apt update
sudo apt install ansible
# On Red Hat-based systems (Fedora, CentOS)
sudo yum install ansible
Or use pip:
pip install ansible
Or use pipx:
pipx install ansible
On macOS
Use Homebrew:
brew install ansible
On Windows
Ansible can be run from inside a Windows Subsystem for Linux (WSL) instance. First, ensure that WSL is installed, then install Ansible in the Linux distribution of your choice, following the Linux installation steps.
Configuring Ansible
Default Ansible configuration settings can be overridden using environment variables. The same variables can be used to override settings in the ansible.cfg file in ini format. Typically, environment variables are in capital letters, while the corresponding configuration settings are in lowercase.
Environment Variable
ansible.cfg Variable
ansible.cfg Section
Description
ANSIBLE_CONFIG
N/A
N/A
Specifies the path to the Ansible configuration file.
ANSIBLE_DEBUG
debug
[defaults]
Enables or disables debug output. Set to True for verbose debug information.
ANSIBLE_INVENTORY
inventory
[defaults]
Path to the inventory file or script.
ANSIBLE_NOCOLOR
nocolor
[defaults]
Disables colored output in Ansible.
ANSIBLE_FORCE_COLOR
force_color
[defaults]
Forces colored output even when not in a TTY.
ANSIBLE_HOST_KEY_CHECKING
host_key_checking
[defaults]
Enables or disables SSH host key checking.
ANSIBLE_REMOTE_USER
remote_user
[defaults]
Default remote user for SSH connections.
ANSIBLE_PRIVATE_KEY_FILE
private_key_file
[defaults]
Specifies the private key file for SSH.
ANSIBLE_TIMEOUT
timeout
[defaults]
Connection timeout duration in seconds.
ANSIBLE_ROLES_PATH
roles_path
[defaults]
Specifies the path to Ansible roles.
ANSIBLE_LIBRARY
library
[defaults]
Path to custom module directories.
ANSIBLE_RETRY_FILES_ENABLED
retry_files_enabled
[defaults]
Enables or disables the creation of retry files.
ANSIBLE_VAULT_PASSWORD_FILE
vault_password_file
[defaults]
Path to the Ansible vault password file.
ANSIBLE_VAULT_IDENTITY_LIST
vault_identity_list
[defaults]
List of vault identities for decryption.
ANSIBLE_STDOUT_CALLBACK
stdout_callback
[defaults]
Sets the default callback plugin for output formatting.
ANSIBLE_CALLBACK_WHITELIST
callback_whitelist
[defaults]
List of callback plugins allowed to execute.
ANSIBLE_FORKS
forks
[defaults]
Number of parallel processes to use.
ANSIBLE_ASK_VAULT_PASS
ask_vault_pass
[defaults]
Determines whether Ansible prompts for the vault password by default.
ANSIBLE_TRANSPORT
transport
[defaults]
Specifies the connection type (e.g., SSH, WinRM).
ANSIBLE_GATHERING
gathering
[defaults]
Configures the default fact gathering behavior.
ANSIBLE_GATHER_SUBSET
gather_subset
[defaults]
Specifies a subset of facts to gather.
ANSIBLE_SSH_ARGS
ssh_args
[ssh_connection]
Extra arguments to pass to the SSH command.
ANSIBLE_SSH_RETRIES
retries
[ssh_connection]
Specifies the number of attempts Ansible will make to connect via SSH before giving up.
ANSIBLE_BECOME
become
[privilege_escalation]
Enables or disables privilege escalation. The default is False.
ANSIBLE_BECOME_METHOD
become_method
[privilege_escalation]
The method used for privilege escalation, the default is sudo.
ANSIBLE_BECOME_USER
become_user
[privilege_escalation]
The user to become on privilege escalation, the default is root.
ANSIBLE_BECOME_ASK_PASS
become_ask_pass
[privilege_escalation]
Prompts for a password for privilege escalation, the default is False.
ANSIBLE_GALAXY_SERVER
server
[galaxy]
Specifies the default Galaxy server from which roles are installed.
ANSIBLE_INVENTORY_ENABLED
inventory_enabled
[inventory]
Specifies the enabled inventory plugins. The default is [‘host_list’, ‘script’, ‘auto’, ‘yaml’, ‘ini’, ‘toml’].
Replace the IP addresses and ansible_ssh_user with your server details.
Ansible Host Variables
Variable
Description
ansible_connection
The type of connection to the host. The default is 'smart'. It supports SSH (smart, ssh, paramiko) and other types.
ansible_host
The hostname or IP to connect to, if different from the alias.
ansible_port
The connection port number. The default is 22 for SSH.
ansible_user
The username for connecting to the host.
ansible_password
The password for authentication (use vault for security).
ansible_ssh_private_key_file
The private key file for SSH, useful for multiple keys.
ansible_ssh_common_args
The common arguments appended to sftp, scp, ssh commands.
ansible_sftp_extra_args
The extra arguments for the sftp command line.
ansible_scp_extra_args
The extra arguments for the scp command line.
ansible_ssh_extra_args
The extra arguments for the ssh command line.
ansible_ssh_pipelining
Whether to use SSH pipelining, overrides ansible.cfg setting.
ansible_ssh_executable
Overrides the default system ssh, added in version 2.2.
ansible_become
Forces privilege escalation, equivalent to ansible_sudo or ansible_su.
ansible_become_method
Sets the privilege escalation method.
ansible_become_user
Sets the user for privilege escalation.
ansible_become_password
Sets the privilege escalation password (use vault for security).
ansible_become_exe
Sets the executable for the escalation method.
ansible_become_flags
Flags for the selected escalation method, can be set in ansible.cfg.
ansible_shell_type
The shell type of the target system. The default is Bourne (sh) compatible.
ansible_python_interpreter
The Python interpreter path on the target host.
ansible_*_interpreter
The generic interpreter setting, works like ansible_python_interpreter. New in version 2.1.
ansible_shell_executable
The shell executable Ansible uses on the target, overrides ansible.cfg.
This table provides a summary of the host-specific variables in Ansible. For detailed information and examples, refer to the official Ansible documentation.
Testing Your Setup
To ensure that Ansible can communicate with your managed nodes, use the ping module:
---
- name: Run a Commandhosts: alltasks:
- name: Run a Commandcommand: uptime
Running a Shell Command
Ad-hoc:
ansible all -m shell -a "echo $TERM"
Playbook:
---
- name: Run a Shell Commandhosts: alltasks:
- name: Run a Shell Commandshell: echo $TERM
Running a Raw Command
Ad-hoc:
ansible all -m raw -a "echo $TERM"
Playbook:
---
- name: Run a Raw Commandhosts: alltasks:
- name: Run a Raw Commandraw: echo $TERM
Copying a File
Ad-hoc:
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts"
Playbook:
---
- name: Copy a Filehosts: alltasks:
- name: Copy a Filecopy:
src: /etc/hostsdest: /tmp/hosts
Installing a Package
Ad-hoc:
ansible all -m apt -a "name=nginx state=present"
Playbook:
---
- name: Install a Packagehosts: alltasks:
- name: Install a Packageapt:
name: nginxstate: present
Restarting a Service
Ad-hoc:
ansible all -m service -a "name=nginx state=restarted"
Playbook:
---
- name: Restart a Servicehosts: alltasks:
- name: Restart a Serviceservice:
name: nginxstate: restarted
Copying a File with Permissions
Ad-hoc:
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts owner=root group=root mode=0644"
Playbook:
---
- name: Copy a File with Permissionshosts: alltasks:
- name: Copy a File with Permissionscopy:
src: /etc/hostsdest: /tmp/hostsowner: rootgroup: rootmode: 0644
Copying a File with Permissions and Context
Ad-hoc:
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts owner=root group=root mode=0644 seuser=system_u serole=object_r"
Playbook:
---
- name: Copy a File with Permissions and Contexthosts: alltasks:
- name: Copy a File with Permissions and Contextcopy:
src: /etc/hostsdest: /tmp/hostsowner: rootgroup: rootmode: 0644seuser: system_userole: object_r
---
- name: Capture Output and Show Only Specific Fieldshosts: alltasks:
- name: Capture Output and Show Only Specific Fieldscommand: echo "Hello World!"register: output
- debug:
var: output.stdout
Capture Output and Show Only Specific Fields with Jinja2
---
- name: Capture Output and Show Only Specific Fields with Jinja2hosts: alltasks:
- name: Capture Output and Show Only Specific Fields with Jinja2command: echo "Hello World!"register: output
- debug:
msg: "{{ output.stdout }}"
Gathering Facts
Gathering Facts for All Hosts
ansible all -m setup
Gathering Facts for a Specific Host
ansible all -m setup -a "filter=ansible_eth*"
Gathering Facts for a Specific Host and Saving to a File
ansible all -m setup -a "filter=ansible_eth*" --tree /tmp/facts
Variables
Setting a Variable
---
- name: Setting a Variablehosts: localhostvars:
my_var: 123tasks:
- name: Setting a Variabledebug:
var: my_var
- name: Setting a Variable (debug)debug:
msg: "{{ my_var }}"
Setting a Variable with Multiple Lines
---
- name: Setting a Variable with Multiple Lineshosts: localhostvars:
my_var: > Hello World!tasks:
- name: Setting a Variable with Multiple Linesdebug:
var: my_var
- name: Setting a Variable with Multiple Lines (debug)debug:
msg: "{{ my_var }}"
Setting a Variable with Multiple Lines and Indentation
---
- name: Setting a Variable with Multiple Lines and Indentationhosts: localhostvars:
my_var: | Hello World! This is indented.tasks:
- name: Setting a Variable with Multiple Lines and Indentationdebug:
var: my_var
- name: Setting a Variable with Multiple Lines and Indentation (debug)debug:
msg: "{{ my_var }}"
---
- name: When with Multiple Conditionshosts: localhostvars:
my_var: 123tasks:
- name: When with Multiple Conditionsdebug:
msg: "Hello World!"when:
- my_var == 123
- my_var != 456
Loops
Looping Over a List
---
- name: Looping Over a Listhosts: localhostvars:
my_list:
- 123
- 456
- 789tasks:
- name: Looping Over a Listdebug:
msg: "{{ item }}"loop: "{{ my_list }}"
Looping Over a Dictionary
---
- name: Looping Over a Dictionaryhosts: localhostvars:
my_dict:
key1: 123key2: 456key3: 789tasks:
- name: Looping Over a Dictionarydebug:
msg: "{{ item.key }}: {{ item.value }}"loop: "{{ my_dict | dict2items }}"
Looping Over a Dictionary Using "with_dict"
---
- name: Looping Over a Dictionary with Nested Itemshosts: localhostvars:
my_dict:
key1:
- 123
- 456
- 789key2:
- 123
- 456
- 789key3:
- 123
- 456
- 789tasks:
- name: Looping Over a Dictionary with Nested Itemsdebug:
msg: "Key: {{ item.key }}, Values: {{ item.value }}"with_dict: "{{ my_dict }}"
Looping Over a List with "with_items"
---
- name: Looping Over a List with with_itemshosts: localhostvars:
my_list:
- 123
- 456
- 789tasks:
- name: Looping Over a List with with_itemsdebug:
msg: "{{ item }}"with_items: "{{ my_list }}"
Handlers
Using Handlers
---
- name: Using Handlershosts: localhosttasks:
- name: Using Handlersdebug:
msg: "Hello World!"notify: My Handlerhandlers:
- name: My Handlerdebug:
msg: "This is my handler."
Using Handlers with Multiple Tasks
---
- name: Using Handlers with Multiple Taskshosts: localhosttasks:
- name: Using Handlers with Multiple Tasksdebug:
msg: "Hello World!"notify: My Handler
- name: Using Handlers with Multiple Tasksdebug:
msg: "Hello World!"notify: My Handlerhandlers:
- name: My Handlerdebug:
msg: "This is my handler."
Using Handlers with Multiple Tasks and Different Handlers
---
- name: Using Handlers with Multiple Tasks and Different Handlershosts: localhosttasks:
- name: Using Handlers with Multiple Tasks and Different Handlersdebug:
msg: "Hello World!"notify: My Handler 1
- name: Using Handlers with Multiple Tasks and Different Handlersdebug:
msg: "Hello World!"notify: My Handler 2handlers:
- name: My Handler 1debug:
msg: "This is my handler 1."
- name: My Handler 2debug:
msg: "This is my handler 2."
Conditional Execution
Using "ignore_errors" to Continue Execution Even After Failures
---
- name: Using ignore_errors to Continue Execution Even After Failureshosts: localhosttasks:
- name: Using ignore_errors to Continue Execution Even After Failurescommand: /bin/falseignore_errors: yes
- name: Using ignore_errors to Continue Execution Even After Failuresdebug:
msg: "Hello World!"
Using "changed_when" to Control When a Task Is Considered Changed
---
- name: Using changed_when to Control When a Task Is Considered Changedhosts: localhosttasks:
- name: Using changed_when to Control When a Task Is Considered Changedcommand: /bin/falseregister: outputchanged_when: output.rc != 2
- name: Using changed_when to Control When a Task Is Considered Changeddebug:
msg: "Hello World!"
Using "failed_when" to Control When a Task Is Considered Failed
---
- name: Example playbook with failed_whenhosts: localhosttasks:
- name: Example playbook with failed_when (will fail)command: /bin/falseregister: output# The normal exit code for /bin/false is 1 failed_when: output.rc == 2
- name: Example playbook with failed_whendebug:
msg: "Hello World!"
Failing a Playbook with "fail"
---
- name: Failing a Playbook with failhosts: localhosttasks:
- name: Failing a Playbook with failfail:
msg: "This task will always fail."
---
- name: Running a Task Asynchronouslyhosts: localhosttasks:
- name: Running a Task Asynchronouslycommand: /bin/bash -c "for i in `seq 1 5`; do echo $i; sleep 1; done"async: 60poll: 0
Checking the Status of Asynchronous Tasks
---
- name: Rolling Update with Timeouthosts: localhosttasks:
- name: Start the application update (async)command: /bin/bash -c "for i in `seq 1 5`; do echo $i; sleep 1; done"async: 60poll: 0register: update_result
- name: Wait for the update to completeasync_status:
jid: "{{ update_result.ansible_job_id }}"register: job_resultuntil: job_result.finishedretries: 60# Check the status every 10 seconds (60 times)
- name: Check if the update was successfuldebug:
msg: "Update successful"when: job_result.finished
Roles
Creating a Role
ansible-galaxy init my_role
Using a Role
---
- name: Using a Rolehosts: localhostroles:
- my_role
Using a Role with Variables
---
- name: Using a Role with Variableshosts: localhostroles:
- role: my_rolevars:
my_var: 123
Using a Role with Multiple Variables
---
- name: Using a Role with Multiple Variableshosts: localhostroles:
- role: my_rolevars:
my_var1: 123my_var2: 456
Using a Role with Tags
---
- name: Using a Role with Tagshosts: localhostroles:
- role: my_roletags:
- install
- configure
ansible/awx: AWX provides a web-based user interface, REST API, and task engine built on top of Ansible. It is one of the upstream projects for the Red Hat Ansible Automation Platform.
ansible/ansible-lint: ansible-lint checks playbooks for practices and behavior that could potentially be improved and can fix some of the most common ones for you.
ansible/ansible-lint: ansible-lint checks playbooks for practices and behavior that could potentially be improved and can fix some of the most common ones for you.
nickjj/ansigenome: A tool to help you gather information and manage your Ansible roles.
ansible-community/ara: ARA Records Ansible and makes it easier to understand and troubleshoot.
mitogen-hq/mitogen: Distributed self-replicating programs in Python (Mitogen for Ansible is a completely redesigned UNIX connection layer and module runtime for Ansible.)
Phansible: Phansible - generate Vagrant + Ansible dev environments for PHP.
pixiu-io/kubez-ansible: To provide quick deployment tools for Kubernetes clusters and cloud-native applications by Ansible.
apenella/go-ansible: Go-ansible is a Go package that enables the execution of ansible-playbook or ansible commands directly from Golang applications.
ansible/ansible-runner: A tool and Python library that helps when interfacing with Ansible directly or as part of another system, whether that be through a container image interface, as a standalone tool, or as a Python module that can be imported.
IDE Extensions
VSCode
Ansible extension by Red Hat - This extension provides comprehensive Ansible language support, including syntax highlighting, auto-completion, and integrated linting.
YAML Support - This extension offers enhanced YAML language support with features like schema validation, auto-completion, and hover documentation.
ansible-vault - This extension facilitates the encryption and decryption of Ansible Vault files directly within VSCode, streamlining the process of managing sensitive data.
PyCharm
Ansible support - This plugin provides support for Ansible directly in PyCharm with features such as playbook run configurations, syntax highlighting, and completion for Ansible keywords.
Sublime
Ansible - This package enhances Sublime Text with Ansible syntax highlighting, code snippets, and completions for a better development experience.
GitGutter - This package shows information about files in a git repository, including changes and line modifications directly in the editor.
SideBarEnhancements - This package provides enhancements to the operations on the Sidebar of Files and Folders, improving file management in Sublime Text.
Sublime Linter - This package is a code-linting framework for Sublime Text 3, helping to identify syntax errors and stylistic issues.
Pretty YAML - This package prettifies YAML for Sublime Text 2 and 3, making YAML files easier to read and edit.
Yamllint - This package is a Sublime wrapper around yamllint, integrating YAML linting into Sublime Text.
Vim
Ansible-vim - This is a Vim plugin for syntax highlighting Ansible's common file types.