简体   繁体   English

Ansible set_fact 列表字典

[英]Ansible set_fact dictionary of lists

I have this code, i'm trying to combine two lists into a dictionary but no luck.我有这个代码,我试图将两个列表组合成一个字典,但没有运气。 Im new to ansible.我是 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 .相反,使用json_query multiselect hash并创建字典列表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:笔记:

  • hostvars and json_query are not necessary to display the variable service_status .不需要hostvarsjson_query来显示变量service_status

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM