Ansible in a Minute · Ansible Core ·
Use merge_variables to combine matching variables
Short answer
Use the community.general.merge_variables lookup to merge every variable whose name matches a prefix, suffix, or regular expression.
Subscribe for updates
Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.
By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.
Request
merge web__profile and api__profile with community.general.merge_variables suffix __profile and print the result
Example
A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.
---
- name: Merge profile variables that share a suffix
hosts: all
gather_facts: false
vars:
web__profile:
listen: 80
api__profile:
backend: 8080
tasks:
- name: Debug merged variables
ansible.builtin.debug:
msg: "{{ lookup('community.general.merge_variables', '__profile', pattern_type='suffix') }}"How it works
The lookup finds every variable whose name ends with __profile and merges those mappings. This play prints a dictionary with listen 80 and backend 8080.
When to use it
- Combining role defaults that share a suffix
- Building one config map from several host or group variables
Requirements
- Ansible: >=2.14
- Collection: community.general
- community.general collection installed
Validation
- Syntax validated
- Not execution-tested
- Last verified 2026-10-11
Notes
pattern_type can be suffix, prefix, or regex. Matching keys from later variables replace earlier values. Use combine when you already have two named dictionaries. Use merge_variables when you want every variable that matches a name pattern.
Reference
- Using the merge_variables lookup (Ansible docs)
- community.general.merge_variables (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.