BacklogZero®

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.

Ansible in a Minute — merge_variables

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.

YAML
---
# Prompt: merge web__profile and api__profile with community.general.merge_variables suffix __profile and print the result
- name: Merge web__profile and api__profile with community.general.merge_variables suffix __profile and print the result
  hosts: all
  gather_facts: false
  vars:
    web__profile:
      key1: value1
      key2: value2
    api__profile:
      key2: updated_value2
      key3: value3
  tasks:
    - name: Merge web__profile and api__profile
      ansible.builtin.set_fact:
        merged_result: "{{ lookup('community.general.merge_variables', '__profile', pattern_type='suffix', override='ignore') }}"

    - name: Print the merged result
      ansible.builtin.debug:
        var: merged_result

How it works

The lookup finds every variable whose name ends with __profile and merges those mappings. Default override is error when a key appears twice. override='ignore' allows the merge. Variables are sorted by name, so web__profile overwrites key2 from api__profile.

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-13

Notes

pattern_type can be suffix, prefix, or regex. Matching keys from later names replace earlier values when override is ignore or warn. Use combine when you already have two named dictionaries. Use merge_variables when you want every variable that matches a name pattern.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today →

Related guides

← Back to Ansible in a Minute

Use merge_variables to combine matching variables · Level Up Labs