Xenia Ioannidou
Xenia Ioannidou

Reputation: 87

how can I update a dictionary in Ansible

I am creating a simple dictionary in ansible which is this one:

"types_dict": {
    "name1": "Ethernet",
    "name2": "Ethernet",
    "name3": "Software-Pseudo",
    "name4": "Ethernet",
    "name5": "Software-Pseudo",
    "name6": "Ethernet" }

My goal is to loop the dictionary and replace some specific values, the ones "Software-Pseudo" with "Virtual". I have tried the following:

- set_fact:
    types_dict: "{{ types_dict | combine(new_item, recursive=true) }}"
  vars:
    new_item: "{ '{{ item.key }}': { 'type': 'Virtual' } }"
  with_dict: "{{ types_dict }}"

but the problem here is that this one updates all the values in my dictionary, which is something I do not want at all. I tried also the following by adding the "when" statement, but also it is not working:

- set_fact:
    types_dict: "{{ types_dict | combine(new_item, recursive=true) }}"
  vars:
    new_item: "{ '{{ item.key }}': { 'type': 'Virtual' } }"
    when: "{{ item.value }} == Software-Pseudo"
  with_dict: "{{ types_dict }}"

I also tried when: "{{ item.value }} == 'Software-Pseudo'" and many other things like this.

Any ideas on how to fix this ?

Upvotes: 2

Views: 3476

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

The task does the job. Items can be added to the list types_new if needed

    - set_fact:
        types_dict: "{{ types_dict|combine({item.0.key: item.1.replace}) }}"
      with_nested:
        - "{{ types_dict|dict2items }}"
        - "{{ types_new }}"
      when: item.0.value is search(item.1.regex)
      vars:
        types_new:
          - {regex: 'Software-Pseudo', replace: 'Virtual'}
    - debug:
        var: types_dict

gives

  types_dict:
    name1: Ethernet
    name2: Ethernet
    name3: Virtual
    name4: Ethernet
    name5: Virtual
    name6: Ethernet

Q: "I have null values like "name2": null in my dictionary, could I handle this in any way so as to replace it with sth else (another value)."

A: Add a line to the types_new. For example

      vars:
        types_new:
          - {regex: 'Software-Pseudo', replace: 'Virtual'}
          - {regex: 'None', replace: 'another_value'}

See the task below how null, None, and 'None' are treated by the search test

    - debug:
        msg: "{{ item.key }} {{ item.value is search('None') }}"
      loop: "{{ my_vars|dict2items }}"
      vars:
        my_vars:
          var1: abc
          var2:
          var3: None
          var4: 'None'

gives

  msg: var1 False
  msg: var2 True
  msg: var3 True
  msg: var4 True

Upvotes: 2

Related Questions