Fail to get values from dictionary in ansible playbook

Viewed 232

I'm trying to get some values from a dictionary in ansible playbook. First, I build the dictionary and it runs correctly. Then, I would compute the output_dict evaluating the values of this dictionary but I have the issue above.

- set_fact:
    state_service: "{{ state_service | default({}) | combine({ item.key : item.value }) }}"
  with_items:
    - { 'key': 'op_state', 'value': "{{Check_Operative_State.results[0].stdout}}"}
    - { 'key': 'ad_state', 'value': "{{Check_Administrative_State.results[0].stdout}}"}

- name: Display the state of service
  debug: msg="{{state_service}}"

- set_fact:
    output_dict: '{{output_dict | default([]) + ["CHECK ERRORS IN SERVICE ************PASSED" if ((item.op_state == "enabled" and item.ad_state == "unlocked") or (item.op_state == "disabled" and item.ad_state == "locked")) else "CHECK ERRORS IN SERVICE **********FAILED"] }}'
  with_items: "{{state_service}}"

The error:

**************************************************
2022-02-04 19:04:45,341 p=4478 u=abcd n=ansible | ok: [localhost] => {
    "msg": {
        "ad_state": "unlocked",
        "op_state": "enabled"
    }
}
2022-02-04 19:04:45,366 p=4478 u=abcd n=ansible | TASK [check : set_fact] ************************************************************************************************************************************************************************
2022-02-04 19:04:45,366 p=4478 u=abcd n=ansible | fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'op_state'\n\nThe error appears to be in '/home/abcd/health/service/script/roles/health/tasks/main.yaml': line 483, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- set_fact:\n  ^ here\n"}
2022-02-04 19:04:45,368 p=4478 u=abcd n=ansible | PLAY RECAP *****************************************************************************************************************************************
1 Answers

Given the list below to simplify the example

  l1:
    - {key: op_state, value: enabled}
    - {key: ad_state, value: unlocked}

Use the filter items2dict to create a dictionary from the list, e.g.

  state_service: "{{ l1|items2dict }}"

gives

  state_service:
    ad_state: unlocked
    op_state: enabled

You can't iterate a dictionary, but you can use dict2items to convert the dictionary to a list, e.g.

    - debug:
        var: item
      loop: "{{ state_service|dict2items }}"

gives (abridged)

  item:
    key: op_state
    value: enabled

  item:
    key: ad_state
    value: unlocked
Related