繁体   English   中英

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

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

我有关注 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"
        }             
    ]
}

我想只获取/打印在 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 -%}

我正在低于 output 以单行打印所有内容:

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

我想要的是dict键值格式/json格式。 如下所示:

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

如何/在我的代码调试消息部分修改什么以高于 output

实现此目的的一种方法是使用when条件设置set_fact

在下面的示例中,我们创建了一个新变量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

产生:

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