# Does anyone use hash\_behaviour=merge?

**URL:** <https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112>\
**Category:** Get Help\
**Tags:** ansible-core\
**Created:** [July 7, 2024, 8:31pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112 "2024-07-07T20:31:32Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![igielskv](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/igielskv/32/4119_2.png) [@igielskv](https://forum.ansible.com/u/igielskv)\
**Post date:** [July 8, 2024, 8:42pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/21 "2024-07-08T20:42:22Z")

</div>

> [@bvitnik](#):
>
> the extra third ssh key must be coming from a third variable

Yes… that is matched from host\_vars, it was just made up for testing, normally should not happen.

---

<div class="post-metadata">

**Author:** ![igielskv](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/igielskv/32/4119_2.png) [@igielskv](https://forum.ansible.com/u/igielskv)\
**Post date:** [July 8, 2024, 8:55pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/22 "2024-07-08T20:55:19Z")

</div>

I’m also experimenting with kind of your approach to this, scratching my head and, are you sure this construction is ok:

`query('ansible.builtin.vars', ['ansible_common_default', 'ansible_common_all'])`

Just seems like brackets should not be there. If I omit them like this:

`query('ansible.builtin.vars', 'ansible_common_default', 'ansible_common_all')`

it works, with brackets I’m getting an error.

---

<div class="post-metadata">

**Author:** ![bvitnik](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/bvitnik/32/4132_2.png) [@bvitnik](https://forum.ansible.com/u/bvitnik)\
**Post date:** [July 8, 2024, 8:56pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/23 "2024-07-08T20:56:16Z")

</div>

Aha. Then I think this is intended behavior of `community.general.merge_variables` plugin, it does not do deduplication of merged lists. @utoddl mentioned that his `mergevars` plugin can do that so you can rely on that. See:

> <https://github.com/utoddl/ansible-plugins/blob/main/plugins/lookup/mergevars.py>

`dedup` option.

My advice would be to organize your vars in such a way that merging does not result in duplicated list elements. It should be possible, just think of what is common for all hosts and what is specific.

Merging dicts is tricky. I prefer flat variables. More control over (de)duplication that way.

---

<div class="post-metadata">

**Author:** ![bvitnik](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/bvitnik/32/4132_2.png) [@bvitnik](https://forum.ansible.com/u/bvitnik)\
**Post date:** [July 8, 2024, 8:58pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/24 "2024-07-08T20:58:55Z")

</div>

> I’m also experimenting with kind of your approach to this, scratching my head and, are you sure this construction is ok.

I was writing from my head 😄, screwed the syntax I guess. Sorry.

**Update:**

To be more elaborate, both of these calls are valid and identical:

`query('ansible.builtin.vars', *['ansible_common_default', 'ansible_common_all'])`

and the one you ended up with:

`query('ansible.builtin.vars', 'ansible_common_default', 'ansible_common_all')`

Note the `*` sign in the first example, that’s what was missing in my original post.

… but, the first one is more powerful because argument list can be a variable itself like so:

```yaml
vars:
  ansible_common:
  - "ansible_common_default"
  - "ansible_common_all"

and then somewhere:

query('ansible.builtin.vars', *ansible_common)

```

---

<div class="post-metadata">

**Author:** ![igielskv](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/igielskv/32/4119_2.png) [@igielskv](https://forum.ansible.com/u/igielskv)\
**Post date:** [July 8, 2024, 9:39pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/25 "2024-07-08T21:39:04Z")

</div>

Thanks… appreciate that. Do you know can this be improved slightly to include what matches `'^ansible_common_'` all the vars with unpredictable suffix?

Something like this:

`"{{ query('ansible.builtin.vars', query('ansible.builtin.varnames', '^ansible_common_')) }}"`

But this above does not work, I have some syntax error here, just can’t figure out now proper construction which could than be used as input for ansible.builtin.combine.

---

<div class="post-metadata">

**Author:** ![bvitnik](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/bvitnik/32/4132_2.png) [@bvitnik](https://forum.ansible.com/u/bvitnik)\
**Post date:** [July 8, 2024, 9:43pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/26 "2024-07-08T21:43:02Z")

</div>

Sure:

```auto
"{{ query('ansible.builtin.vars', *query('ansible.builtin.varnames', '^ansible_common_')) }}"

```

Note the `*` signs.

---

<div class="post-metadata">

**Author:** ![utoddl](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/utoddl/32/249_2.png) [@utoddl](https://forum.ansible.com/u/utoddl)\
**Post date:** [July 9, 2024, 1:38am UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/27 "2024-07-09T01:38:20Z")

</div>

> [@bvitnik](#):
>
> organize your vars in such a way that merging does not result in duplicated list elements

Not always possible, though. Say you have

- role defaults of `[1,2,3]`,
- host group `alpha` adds `[6,8,10]`,
- host group `beta` adds `[7,8,9]`.

Now host `polyglot` is in both groups `alpha` and `beta`, so it ends up with `[1,2,3, 6,8,10, 7,8,9]`. Somewhere you have to deal with the doubled `8`, either in the merge plugin, or the Jinja that calls it, or the task(s) that consume the list. None of those are inherently wrong, but that complexity must exist somewhere. I’d suggest the most right/least wrong answer is: “maintainers choice”.

And just for argument’s sake, I can imagine a situation where the doubled `8` should be preserved, so no blanket solutions (“merge plugin always dedupes”) allowed!

For what seems like such a simple problem, there sure are lots of ways to make it messy.

---

<div class="post-metadata">

**Author:** ![utoddl](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/utoddl/32/249_2.png) [@utoddl](https://forum.ansible.com/u/utoddl)\
**Post date:** [July 9, 2024, 1:54am UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/28 "2024-07-09T01:54:53Z")

</div>

> [@igielskv](#):
>
> Why you initialize with `sssd_allow_groups_default` and this you are merging with `regex='^sssd_allow_groups_'`? Would not be `sssd_allow_groups_default` also matched with regex?

Good question. It’s part of why I selected that as an example. The merge order for `mergevars` is defined such that explicitly named variables and in-line values are merged in the order listed. After that, variables matching the optional `regex` are sorted by name _ **excluding any already merged** _ because they were listed explicitly, and then the remaining matching variables are merged. This allows you to ensure you start with, for example, role defaults which may be augmented or replaced by other data in the merge process.

---

<div class="post-metadata">

**Author:** ![igielskv](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/igielskv/32/4119_2.png) [@igielskv](https://forum.ansible.com/u/igielskv)\
**Post date:** [July 9, 2024, 9:14am UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/29 "2024-07-09T09:14:06Z")

</div>

> [@bvitnik](#):
>
> Note the `*` signs.

Wau!!! was it that simple?

…now this does almost exactly what I want:

`ansible_common: "{{ lookup('ansible.builtin.vars', *query('ansible.builtin.varnames', '^ansible_common_')) | ansible.builtin.combine(recursive=true) }}"`

Note: Doesn’t address any de-duplication inside merged structures, etc. (so functionality in comparison to hash\_behaviour=merge still little lacks behind :slight\_smile), but it’s already acceptable and non-standard hash\_behaviour is not needed.

Also how one would compare plugins from `ansible.builtin` vs `community.general` in terms of performance, reliability, etc. (if there is a choice).

(because here I could have use either `community.general.merge_variables` vs `ansible.builtin.vars` in conclusion with `ansible.builtin.combine`, what would be preferd? I don’t know, I just tend to incline to `ansible.builtin` when I can.)

Also many thanx to you ‘bvitnik’ for your help.

---

<div class="post-metadata">

**Author:** ![utoddl](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/utoddl/32/249_2.png) [@utoddl](https://forum.ansible.com/u/utoddl)\
**Post date:** [July 9, 2024, 11:04am UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/30 "2024-07-09T11:04:47Z")

</div>

With regard to de-duplication, `ansible.builtin.combine` has an optional [`list_merge`](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/combine_filter.html#parameter-list_merge) parameter where two of its allowed values remove duplicates _created by the merge_.

> Behavior when encountering list elements.  
> Choices:  
> - “append”: append newer entries to the older ones  
> - “append\_rp”: append newer entries to the older ones, overwrite duplicates  
> - “keep”: discard newer entries  
> - “prepend”: insert newer entries in front of the older ones  
> - “prepend\_rp”: insert newer entries in front of the older ones, discard duplicates  
> - “replace” (default): overwrite older entries with newer ones

---

<div class="post-metadata">

**Author:** ![bvitnik](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/bvitnik/32/4132_2.png) [@bvitnik](https://forum.ansible.com/u/bvitnik)\
**Post date:** [July 9, 2024, 11:59am UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/31 "2024-07-09T11:59:40Z")

</div>

> [@utoddl](#):
>
> > [@bvitnik](#):
> >
> > organize your vars in such a way that merging does not result in duplicated list elements
> 
> Not always possible, though. Say you have
> 
> - role defaults of `[1,2,3]`,
> - host group `alpha` adds `[6,8,10]`,
> - host group `beta` adds `[7,8,9]`.

In this particular example, you can deduplicate `8` just by reorganizing variables and groups like so:

- role defaults of `[1,2,3]`,
- host group `alpha` adds `[6,10]`,
- host group `beta` adds `[7,9]`,
- host group `alpha_beta` adds `[8]`.

Either that or `8` is really a shared value and should go to e.g. role defaults `[1,2,3,8]`.

---

<div class="post-metadata">

**Author:** ![utoddl](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/utoddl/32/249_2.png) [@utoddl](https://forum.ansible.com/u/utoddl)\
**Post date:** [July 9, 2024, 12:12pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/32 "2024-07-09T12:12:40Z")

</div>

Okay, true enough, it is _possible_. I should amend my list:

> [@utoddl](#):
>
> Somewhere you have to deal with the doubled `8`, either in the merge plugin, or the Jinja that calls it, or the task(s) that consume the list.

to include “or modifying hosts/host groups.”  
But in this admittedly contrived example, creating a host group to avoid deduping a list is going to raise some maintainer’s eyebrows some day.

You’re not wrong. The point remains though: the complexity will exist somewhere. I stick by the statement, “the most right/least wrong answer is: maintainer’s choice.”

---

<div class="post-metadata">

**Author:** ![bvitnik](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/bvitnik/32/4132_2.png) [@bvitnik](https://forum.ansible.com/u/bvitnik)\
**Post date:** [July 9, 2024, 12:15pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/33 "2024-07-09T12:15:34Z")

</div>

> [@igielskv](#):
>
> > [@bvitnik](#):
> >
> > Note the `*` signs.
> 
> Wau!!! was it that simple?
> 
> …now this does almost exactly what I want:
> 
> `ansible_common: "{{ lookup('ansible.builtin.vars', *query('ansible.builtin.varnames', '^ansible_common_')) | ansible.builtin.combine(recursive=true) }}"`

Yes 😄… Now you better understand how things work and you finally came to the exact code I’m using 😀

> [@](#):
>
> Also how one would compare plugins from `ansible.builtin` vs `community.general` in terms of performance, reliability, etc. (if there is a choice).
> 
> (because here I could have use either `community.general.merge_variables` vs `ansible.builtin.vars` in conclusion with `ansible.builtin.combine`, what would be preferd? I don’t know, I just tend to incline to `ansible.builtin` when I can.)
> 
> Also many thanx to you ‘bvitnik’ for your help.

There is probably no comprehensive benchmark done so no way to tell. Using `community.general.merge_variables` should be faster compared to chaining `ansible.builtin.vars`, `ansible.builtin.varnames` and `ansible.builtin.combine` just because you call one plugin instead of three. On the other hand, performance difference should be negligible compared to the general “slownes” of Ansible itself in regard to SSH-ing to the host, uploading module code, running it etc.

In terms of code quality of `community.general` collection, it should be on par with Ansible itself because all the same contribution guidelines and requirements are in place. Most of the code in `community.general` collection was part of the Ansible package back in the days when collections didn’t exist.

---

<div class="post-metadata">

**Author:** ![bvitnik](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/bvitnik/32/4132_2.png) [@bvitnik](https://forum.ansible.com/u/bvitnik)\
**Post date:** [July 9, 2024, 12:16pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/34 "2024-07-09T12:16:36Z")

</div>

> [@utoddl](#):
>
> Okay, true enough, it is _possible_. I should amend my list:
> 
> > [@utoddl](#):
> >
> > Somewhere you have to deal with the doubled `8`, either in the merge plugin, or the Jinja that calls it, or the task(s) that consume the list.
> 
> to include “or modifying hosts/host groups.”  
> But in this admittedly contrived example, creating a host group to avoid deduping a list is going to raise some maintainer’s eyebrows some day.
> 
> You’re not wrong. The point remains though: the complexity will exist somewhere. I stick by the statement, “the most right/least wrong answer is: maintainer’s choice.”

True, true 🙂…

---

<div class="post-metadata">

**Author:** ![igielskv](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/igielskv/32/4119_2.png) [@igielskv](https://forum.ansible.com/u/igielskv)\
**Post date:** [July 9, 2024, 12:30pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/35 "2024-07-09T12:30:40Z")

</div>

> [@utoddl](#):
>
> `ansible.builtin.combine` has an optional [`list_merge`](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/combine_filter.html#parameter-list_merge) parameter

Oh man… I should pay more attention to the docs. 🫢

This is it:

`ansible_common: "{{ lookup('ansible.builtin.vars', *query('ansible.builtin.varnames', '^ansible_common_')) | ansible.builtin.combine(list_merge='append_rp', recursive=true) }}"`

I have introduced many duplicates for testing at various places between groups and hosts vars, and behavior is there! I see, I can control everything here.

Thanks a lot Todd!

---

<div class="post-metadata">

**Author:** ![igielskv](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/igielskv/32/4119_2.png) [@igielskv](https://forum.ansible.com/u/igielskv)\
**Post date:** [July 9, 2024, 12:42pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/36 "2024-07-09T12:42:42Z")

</div>

Thanks for the thoughts and clarification about community.general and ansible.builtin - makes sense - and I’ll keep that in mind.

---

<div class="post-metadata">

**Author:** ![Thulium-Drake](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/thulium-drake/32/833_2.png) [@Thulium-Drake](https://forum.ansible.com/u/Thulium-Drake)\
**Post date:** [July 9, 2024, 2:05pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/37 "2024-07-09T14:05:22Z")

</div>

Well, I don’t have anything to add to this discussion anymore, but it was/is a very interesting read and I am definitely stealing that for in my cookbook of tips 'n tricks 😉

---

<div class="post-metadata">

**Author:** ![bvitnik](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/bvitnik/32/4132_2.png) [@bvitnik](https://forum.ansible.com/u/bvitnik)\
**Post date:** [July 9, 2024, 2:07pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/38 "2024-07-09T14:07:27Z")

</div>

No problem, just note the author 😁

---

<div class="post-metadata">

**Author:** ![Thulium-Drake](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/thulium-drake/32/833_2.png) [@Thulium-Drake](https://forum.ansible.com/u/Thulium-Drake)\
**Post date:** [July 9, 2024, 2:32pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/39 "2024-07-09T14:32:53Z")

</div>

So, I’ve made a sample playbook with your version (and, for good measure also c.g.merge\_variables), which will (hopefully) clearly illustrate when you should use which (assuming maintainability and readability is a factor)

```auto
---
  - name: Example of merging dicts
    hosts: localhost
    gather_facts: false # Speed up the example
    vars: # Note that these could be definied anywhere in inventory
      group1_settings__to_merge:
        some_setting: "foo"
        some_list:
          - "foo"
          - "bar"
        another_setting: "bar"
      group2_settings__to_merge:
        some_setting: "foo"
        some_list:
          - "baz"
          - "foo"
        yet_another_setting: "baz"
      group3_settings__to_merge:
        some_setting: "ever"
        some_list:
          - "quxz"
          - "3242"
        a_totally_different_setting: "qux"
      group4_some_other_var: # This won't get merged
        what: ever
    tasks:
    - name: 'varnames | combine -> Show result, deduped last wins'
        ansible.builtin.debug:
        msg: "{{ lookup('ansible.builtin.vars', *query('ansible.builtin.varnames', 'settings__to_merge$')) | ansible.builtin.combine(list_merge='append_rp', recursive=true) }}"
    - name: 'c.g.merge_variables -> Show result as is, must set override to ignore'
        ansible.builtin.debug:
          msg: "{{ lookup('community.general.merge_variables', 'settings__to_merge', pattern_type='suffix', override='ignore') }}"

```

It resolves to this:

```auto
PLAY [Example of merging dicts] *********************************************************************************

TASK [varnames | combine -> Show result, deduped last wins] *****************************************************
ok: [localhost] => 
  msg:
    a_totally_different_setting: qux
    another_setting: bar
    some_list:
    - bar
    - baz
    - foo
    - quxz
    - '3242'
    some_setting: ever
    yet_another_setting: baz

TASK [c.g.merge_variables -> Show result as is, must set override to ignore] ************************************
ok: [localhost] => 
  msg:
    a_totally_different_setting: qux
    another_setting: bar
    some_list:
    - foo
    - bar
    - baz
    - foo
    - quxz
    - '3242'
    some_setting: ever
    yet_another_setting: baz

```

So _unless_ you want/need to have a deduped list of some form, it doesn’t matter. The last addition to the merged list wins (see `some_setting`), but `some_list` is the only thing that really differs.

Maybe (I don’t think my 🐍 skills are up to snuff for this) it would be an option for `c.g.merge_variables` to have an additional override mode, borrowing a few (I’d say only append\_rp) from `a.b.combine`. Because it is aware of the fact there is a list in there:

```auto
TASK [c.g.merge_variables -> Show result] ***********************************************************************
fatal: [localhost]: FAILED! => 
  msg: 'An unhandled exception occurred while running the lookup plugin ''community.general.merge_variables''. Error was a <class ''ansible.errors.AnsibleError''>, original message: The key ''some_setting'' with value ''foo'' will be overwritten with value ''ever'' from ''group3_settings __to_merge.some_setting''. The key ''some_setting'' with value ''foo'' will be overwritten with value ''ever'' from ''group3_settings__ to_merge.some_setting'''

```

---

<div class="post-metadata">

**Author:** ![utoddl](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/utoddl/32/249_2.png) [@utoddl](https://forum.ansible.com/u/utoddl)\
**Post date:** [July 9, 2024, 2:47pm UTC](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112/40 "2024-07-09T14:47:29Z")

</div>

What was the code which produced that last “`TASK [c.g.merge_variables -> Show result]`” output?

[Previous page](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112.md?page=1)

[Next page](https://forum.ansible.com/t/does-anyone-use-hash-behaviour-merge/7112.md?page=3)
