Last active
June 3, 2024 15:51
-
-
Save dbowling/5f6fd834c88606a7fc5aea37773f1dca to your computer and use it in GitHub Desktop.
How to merge variables in Ansible using the `community.general.merge_variables`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- name: Example merge playbook | |
hosts: "localhost" | |
vars: | |
zabbix_agent__default__host_groups: # defined as the initial value | |
# will be included in the merge | |
- Linux | |
zabbix_agent__env__host_groups: # merged | |
- Bar | |
zabbix_agent__host__host_groups: # merged | |
- Foo | |
not_merged__host__host_groups: # not merged | |
- BAM | |
zabbix_agent__host__not_merged: # not merged | |
- BAM | |
zabbix_agent_merge_regex: '^zabbix_agent__.+__host_groups$' | |
tasks: | |
- name: Set host groups fact | |
# the `| unique` is probably important in most use cases! | |
set_fact: | |
combined_host_groups: "{{ lookup('community.general.merge_variables', zabbix_agent_merge_regex, initial_value=zabbix_agent__default__host_groups) | unique }}" | |
- name: Debug merged result | |
debug: | |
var: combined_host_groups | |
# Output: | |
# ok: [localhost] => | |
# combined_host_groups: | |
# - Linux | |
# - Bar | |
# - Foo | |
# Tip! | |
# If you include `zabbix_agent__ansible__host_groups: "{{ group_names | list }}"` in `vars`, you will also get the hosts group memberships. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment