Merging hashes

In the previous section, we focused on the precedence in which variables will override each other. The default behavior of Ansible is that any overriding definition for a variable name will completely mask the previous definition of that variable. However, that behavior can be altered for one type of variable; the hash. A hash variable (a dictionary, in Python terms) is a dataset of keys and values. Values can be of different types for each key, and can even be hashes themselves for complex data structures.

In some advanced scenarios, it is preferable to replace just one bit of a hash or add to an existing hash rather than replacing the hash altogether. To unlock this ability, a configuration change is necessary in the Ansible config file. The configuration entry is hash_behavior, which either takes the value replace or merge. A setting of merge will instruct Ansible to merge or blend the values of two hashes when presented with an override scenario, rather than assume the default of replace, which will completely replace the old variable data with the new data.

Let's walk through an example of the two behaviors. We will start with a hash loaded with data and simulate a scenario where a different value for the hash is provided as a higher-priority variable.

This is the starting data:

hash_var: 
  fred: 
    home: Seattle 
    transport: Bicycle 

This is the new data loaded via include_vars:

hash_var: 
  fred: 
    transport: Bus 

With the default behavior, the new value for hash_var will be as follows:

hash_var: 
  fred: 
    transport: Bus 

However, if we enable the merge behavior, we will get the following result:

hash_var: 
  fred: 
    home: Seattle 
    transport: Bus 

There are even more nuances and undefined behaviors when using merge and, as such, it is strongly recommended to only use this setting if absolutely necessary.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.136.170