I am reading some Ansible code that looks like this:
---
- meta: end_play
when: centos is defined
- name: Set centos variable
set_fact:
centos: "{{ hostvars[item]['ansible_distribution_version'][0:1] }}"
with_inventory_hostnames: all
delegate_to: "{{ item }}"
delegate_facts: true
run_once: true
I have nobody to ask as the developer is long gone. Is this a common Ansible pattern?
If so, could someone explain why might this needs to be done? Are they trying to stop recursion or does it just look cool?
2
Answers
Be careful not to confuse playbook and play.
You can have multiple plays in a playbook.
Here is an example playbook:
That would still print the
debug
task of the second play, although not printing the one of the first, due to themeta
task:Actual output:
So, yes, most probably, the snippet of YAML you are providing is there to ensure the variable
centos
is defined, and if it is already, skip the whole play to act on the variable in a further play.Given the playbook:
debug
would yield--extra-vars "centos='from extra-vars'"
, it would, then, yieldLet me comment on the second task
This task runs once and iterates set_fact for all hosts. The loop
is equal to
Each iteration is delegated to a host and the facts are delegated too. All these settings do exactly the same as the simple below task