The run_once statement in Ansible

Harnessing the Hidden Power of Ansible’s “run_once” Directive

Luca Berton

--

Introduction

Ansible is a powerful automation tool that makes managing IT infrastructure easier. One of its lesser-known but highly useful directives is “run_once.” While using it at the play level might seem unremarkable, its true potentials reveals itself when employed within a task. Let’s explore the wonders of run_once and how it can simplify complex automation scenarios.

Play Level

At the play level, using `run_once` is equivalent to changing the host selection. Instead of specifying hosts as “foo,” you’d use “foo[0].” This makes it convenient for directing tasks to a specific host but doesn’t necessarily elicit much excitement.

- name: Play level
hosts: host1,host2,host3,host4,host5,host6,host7
run_once: true
tasks:
- name: Print message
ansible.builtin.debug:
msg: Hello World

However, the real enchantment occurs when you use run_once within a task. When you do this, tasks with run_once are executed on a single host, typically the first host in the runlist. This simple feature allows for intricate choreography. For instance, you can send a command to a cluster only once, even if there are multiple equally available…

--

--

Luca Berton

I help creative Automation DevOps, Cloud Engineer, System Administrator, and IT Professional to succeed with Ansible Technology to automate more things everyday