In this tutorial, you will learn how the Ansible dry_run works and how to use it in your playbooks.
What is Ansible Dry_Run?
Ansible Dry_Run, also known as Check mode, is a feature that allows you to check a playbook before executing it on remote hosts. Using the dry_run feature, you can test whether a playbook is valid without making actual changes on the server. It uses the Ansible built-in check feature to read and proof for errors in Playbooks before they are applied to the remote machines.
A common use of the Ansible dry_run feature is when you have a massively complex playbook that may cause downtime on the services on the remote hosts. For example, you can use the dry_run feature to check if the playbook is correct before restarting services.
How to use Ansible Dry_Run
The easiest way to use the dry_run feature is to include the –check or -C options in the ansible-playbook command.
Let us take an example of a playbook that installs an Apache HTTP and UFW firewall and creates a rule to allow HTTP traffic on port 80.
- hosts: all
become: true
gather_facts: no
tasks:
- name: Install Apache HTTP Server
apt:
name: apache2
update_cache: yes
state: latest
- name: Install Firewall
apt:
name: ufw
state: latest
- name: Allow Apache on Firewall
ufw:
rule: allow
port: "80"
proto: tcp
Save the playbook and run it in check mode as shown in the command below:
The above command will run the playbook in check mode. You will notice that the output is similar to when you run the playbook. However, Ansible only reports the changes that would have been applied to the remote hosts.
The second method you can use the Ansible dry_run feature is to use the check_mode parameter in the playbook.
The check_mode is a Boolean value that specifies whether a task should be executed in Check mode.
The following sample playbook tells Ansible to run the “Install Apache” task in check mode.
- hosts: all
become: true
gather_facts: no
tasks:
- name: Install Apache HTTP Server
apt:
name: apache2
update_cache: yes
state: latest
check_mode: yes
Ansible Diff Mode
Ansible also provides you with a diff mode. Diff mode lets you view the changes before and after executing a task.
To use the diff mode in Ansible, use the –diff option with the ansible-playbook command.
The output above shows the changes made when installing the Apache HTTP package.
You can use the diff and dry_run mode to get more output as:
The above command should provide detailed output about the changes made to a remote host.
Wrap Up
This guide gives you a walkthrough of the Ansible dry_run feature and how you can use it to verify your Playbooks. Using the dry_run feature, you can check for errors and understand the changes to be executed on remote hosts before they happen.
Thank you for reading!