senthil
senthil

Reputation: 85

how to set default value if key is not available in dict in ansible play

I am setting fact as dict using host names like below,

set_fact:
      processed_hosts: "{{ processed_hosts | default([]) + [dict(host_name=item, result=hostvars[item]['_OS_upgraded'])] }}"
    with_items:
      - "{{ groups['reachable_a_hosts'] }}"

Its working good when all the host has "_OS_upgraded".

But when task failed in any of the host then "_OS_upgraded" is not set, on that scenario i am getting error when i call this hostvars[item]['_OS_upgraded']

so want to set it false by default if that item is not in hostvars,

Can some one let me know how to do that?

Upvotes: 1

Views: 1286

Answers (1)

senthil
senthil

Reputation: 85

It worked after adding | default(False)

set_fact:
      processed_hosts: "{{ processed_hosts | default([]) + [dict(host_name=item, result=hostvars[item]['_OS_upgraded']|default(False))] }}"
    with_items:
      - "{{ groups['reachable_a_hosts'] }}"

Upvotes: 1

Related Questions