Skip to content

Instantly share code, notes, and snippets.

@reyjrar
Created December 28, 2019 18:16
Show Gist options
  • Save reyjrar/7d4828b6538cae6316536fdcc03e69c6 to your computer and use it in GitHub Desktop.
Save reyjrar/7d4828b6538cae6316536fdcc03e69c6 to your computer and use it in GitHub Desktop.
A task to emulate `-e foo=bar` in a playbook
---
- name: "Set a global variable mid-playbook run"
run_once: true
set_fact:
"{{ global_name }}": "{{ global_value }}"
delegate_to: "{{ _all__hostname }}"
loop: "{{ groups['all'] }}"
loop_control:
loop_var: "_all__hostname"
---
- hosts: some_limited_group
tasks:
- name: "Set a global foo=bar for all hosts, not just some_limited_group"
include_tasks: "set_global_var.yaml"
vars:
global_name: foo
global_value: bar
---
- hosts: some_limited_group
tasks:
# Let's say we have a task to rename hosts and it sets a fact of new_hostname on the host
- include_tasks: "change_host_name.yaml"
# Record this group globally
- include_tasks: "set_global_var.yaml"
vars:
global_name: "target_hosts"
global_value: "{% set colon = joiner(':') %}{% for host in play_hosts %}{{ colon() }}{{ hostvars[host].new_hostname }}{% endfor %}"
- hosts: all
tasks:
- name: "Refresh the inventory to reset all host groups and pick up the hosts at the new hostname"
meta: refresh_inventory
# Host variables are preserved!
- name: "recreate the some_limited_group with the new hosts"
add_host:
group: "some_limited_group"
name: "{{ item }}"
with_inventory_hostnames: "{{ taget_hosts }}"
changed_when: false
- hosts: some_limited_group
tasks:
- debug: msg="{{ inventory_hostname }} is in the group."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment