Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - How to keep appending new keys to a dictionary when using set_fact module with with_items?

Tags:

I want to add keys to a dictionary when using set_fact with with_items. This is a small POC which will help me complete some other work. I have tried to generalize the POC so as to remove all the irrelevant details from it.

When I execute following code it is shows a dictionary with only one key that corresponds to the last item of the with_items. It seems that it is re-creating a new dictionary or may be overriding an existing dictionary for every item in the with_items. I want a single dictionary with all the keys.

Code:

--- - hosts: localhost   connection: local   vars:       some_value: 12345       dict: {}   tasks:      - set_fact: {           dict: "{              {{ item }}: {{ some_value }}              }"             }        with_items:           - 1           - 2           - 3      - debug: msg="{{ dict }}" 
like image 682
Anand Patel Avatar asked Aug 02 '15 14:08

Anand Patel


1 Answers

This can also be done without resorting to plugins, tested in Ansible 2.2.

--- - hosts: localhost   connection: local   vars:     some_value: 12345     dict: {}   tasks:   - set_fact:       dict: "{{ dict | combine( { item: some_value } ) }}"     with_items:       - 1       - 2       - 3   - debug: msg="{{ dict }}" 

Alternatively, this can be written without the complex one-liner with an include file.

  tasks:   - include: append_dict.yml     with_items: [1, 2, 3] 

append_dict.yml:

- name: "Append dict: define helper variable"   set_fact:     _append_dict: "{ '{{ item }}': {{ some_value }} }"  - name: "Append dict: execute append"   set_fact:     dict: "{{ dict | combine( _append_dict ) }}" 

Output:

TASK [debug] ******************************************************************* ok: [localhost] => {     "msg": {         "1": "12345",         "2": "12345",         "3": "12345"     } } 

Single quotes ' around {{ some_value }} are needed to store string values explicitly.

This syntax can also be used to append from a dict elementwise using with_dict by referring to item.key and item.value.

Manipulations like adding pre- and postfixes or hashes can be performed in the same step, for example

    set_fact:       dict: "{{ dict | combine( { item.key + key_postfix: item.value + '_' +  item.value | hash('md5') } ) }}" 
like image 91
Andreas Avatar answered Sep 23 '22 08:09

Andreas