简体   繁体   English

如何使用调试或设置事实模块在 ansible 中使用 Jinja2 获取 dict 键值格式

[英]How to get dict key value format using Jinja2 in ansible using debug or set fact module

I have following output我有关注 output

    TASK [debug] *******************************************************************
    ok: [1.1.1.1] => {
    "msg": [
        {
            "DESCRIP": "server-abc",
            "PORT": "Po3",
            "PROTOCOL": "up",
            "STATUS": "up"
        },
        {
            "DESCRIP": "Leaf-1",
            "PORT": "Po4",
            "PROTOCOL": "up",
            "STATUS": "up"
        },
        {
            "DESCRIP": "server-xyz",
            "PORT": "Po1",
            "PROTOCOL": "up",
            "STATUS": "up"
        },  
        {
            "DESCRIP": "Leaf-2",
            "PORT": "Po2",
            "PROTOCOL": "up",
            "STATUS": "up"
        }             
    ]
}

i want to get/print only blocks which contains "Leaf" in DESCRIP and "Po" in PORT to do this i have below debug with jinj2我想只获取/打印在 DESCRIP 中包含“Leaf”和在 PORT 中包含“Po”的块来执行此操作,我在下面使用 jinj2 进行调试

 - debug:
    msg: >-
           {%- for item in output.parsed -%}
           {%- if ('Leaf' in item.DESCRIP) and ('Po' in item.PORT) -%}
             "DESCRIP": {{item.DESCRIP}},
             "PORT": {{item.PORT}}
           {%- endif -%}
           {%- endfor -%}

i am getting below output printing everything in single line:我正在低于 output 以单行打印所有内容:

TASK [debug] *******************************************************************
ok: [10.2.4.1] => {
    "msg": "\"DESCRIP\": Leaf-1,\n  \"PORT\": Po4\"\"DESCRIP\": Leaf-2,\n  \"PORT\": Po2"
}

what i want is dict key value format/json format.我想要的是dict键值格式/json格式。 like below:如下所示:

[{
    "DESCRIP": "Leaf-1",
    "PORT": "Po4",
},
{
    "DESCRIP": "Leaf-2",
    "PORT": "Po2",
} ]

How/what to modify in my code debug msg section to get above output如何/在我的代码调试消息部分修改什么以高于 output

One way to achieve this, would be to set_fact with when condition.实现此目的的一种方法是使用when条件设置set_fact

In the below example, we create a new variable serv_list (initially empty list), then append the DESCRIP and PORT when the criteria matches.在下面的示例中,我们创建了一个新变量serv_list (最初为空列表),然后当条件匹配时 append DESCRIPPORT

    - set_fact:
        serv_list: '{{ serv_list | default([]) + [ { "DESCRIP": item.DESCRIP, "PORT": item.PORT } ] }}'
      loop: "{{ output.parsed }}"
      when:
        - item.DESCRIP is search('Leaf')
        - item.PORT is search('Po')

    - debug:
        var: serv_list

Produces:产生:

ok: [localhost] => {
    "serv_list": [
        {
            "DESCRIP": "Leaf-1",
            "PORT": "Po4"
        },
        {
            "DESCRIP": "Leaf-2",
            "PORT": "Po2"
        }
    ]
}

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

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