I have this code, i'm trying to combine two lists into a dictionary but no luck. Im new to ansible.
- hosts: localhost
vars:
service_status: {}
location:
tasks:
- name:
command: echo {{ item }}
register: excecute
with_items:
- hello
- world
- name: Setting facts
set_fact:
service_status: "{{service_status | combine({ 'command_status' : {'service': item.item , 'status': item.failed }}, recursive=True) }}"
with_items: "{{ excecute.results }}"
- name:
debug:
msg: "{{ hostvars['localhost'] | json_query('service_status') }}"
the output i got is
TASK [debug]
ok: [localhost] => {
"msg": {
"command_status": {
"service": "world",
"status": false
}
}
}
but i want the output like below
"command_status": [
{
"service": "hello",
"status": false
},
{
"service": "world",
"status": false
}
]
The loop is not necessary to create the list of dictionaries with the selected attributes of the results. Instead, use json_query multiselect hash and create the list of dictionaries cmd_stats . Then combine the dictionary in one step. For example, the tasks below
- name: Setting facts
set_fact:
service_status: "{{ service_status|
combine({'command_status': cmd_stats}) }}"
vars:
cmd_stats: "{{ excecute.results|
json_query('[].{service: item, status: failed}') }}"
- debug:
var: service_status
give
service_status:
command_status:
- service: hello
status: false
- service: world
status: false
Notes:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.