This guide will discuss how you can use the Ansible run_once module to perform a set of operations.
Basic Usage
The Ansible run_once parameter is applied to one specific task you want to be executed on the first host.
The following example playbook shows how you can set the run_once parameter in a playbook.
- hosts: all
# ...
tasks:
- name: run this command once
shell: command
run_once: true
The example playbook above shows the general syntax to implement a run_once task.
Let us look at a few examples and see various use cases of the run_once parameter.
Example 1
We will implement a simple playbook that downloads a zip file from an URL in our first example. Since it does not make sense to repeatedly redownload the file on each host, we can use the run_once parameter.
Take the example playbook shown below:
- hosts: all
gather_facts: yes
tasks:
- name: Download file only once
run_once: true
get_url:
url: https://file-examples-com.github.io/uploads/2017/02/zip_10MB.zip
dest: ~/zip_10MB.zip
- name: unarchive
unarchive:
src: ~/zip_10MB.zip
dest: ~/zip_10MB
The example playbook above will download the file in the first batch and then unarchive it on the remote hosts.
Example 2
The next sample playbook creates an archive from a git repository.
- hosts: all
gather_facts: yes
tasks:
- name: create archive from repo
git:
repo: https://github.com/samples/repo.git
dest: /home/user/repo
archive: /home/user/repo.zip
run_once: true
Example 3
We can also use the run_once parameter to create a backup and then sync the database to the remote hosts using the RSYNC protocol. Consider the example playbook below:
- hosts: all
gather_facts: yes
become: true
tasks:
- name: create a backup archive
archive:
path:
/var/log/
/custom/all
dest: /backup/system0-backup.bz2
format: bz2
remove: no
run_once: true
- name: sync backup with rsync
synchronize:
src: /backup/system0-backup.bz2
dest: rsync://{{inventory_hostname}}/backups
The playbook will create a backup archive on the localhost and sync the files to all remote hosts.
Example 4
The example playbook uses the run_once parameter to send mail to all hosts.
- hosts: all
gather_facts: yes
become: true
tasks:
- name: create a backup archive
local_action:
module: mail
subject: "Mail from Ansible."
to: ubuntu@localhost
body: "Updated to the new Redis version."
run_once: true
The playbook sends mail to a specific user.
Conclusion
This guide shows you how to use the run_once parameter in Ansible to perform a task on a single host and apply the results to other hosts.