Merge Variables/Dictinaries in Ansible

Standard

If you are trying to merge variables in an ansible script and you do not have access to change the ansible configuration (or do not want to do so), follow these steps:

Imagine you have a regular include_vars task:

- include_vars:
  dir: "vars"

The above code adds every file in the vars folder to the facts collection. As an example, consider you have the following file var.yml.

---
site:
  name: "Api Explorer"
  version: "1.0.0-SNAPSHOT"

Step 1 – Create a file inside the homolog folder.

---
site:
  version: "1.0.1"

Step 2 – Create a task in your playbook that loads files and adds them in a separate context, in this case, specific_vars is filled with the contents of files in the homolog folder.

- include_vars:
  dir: "homolog"
  name: specific_vars

Step 3 – Create a task to combine the variables in facts with the variables in specific_vars.

- name: "Combine specific with default variables"
  set_fact: {"{{ item.key }}": "{{ vars[item.key] | combine(item.value) if item.value['keys'] is defined else item.value }}"}
  with_dict: "{{ specific_vars }}"

Now you can run your script and you will see that the value of site.version is 1.0.1 and the variable site.name still exists.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s