Home > Back-end >  How to get dict key value format using Jinja2 in ansible using debug or set fact module
How to get dict key value format using Jinja2 in ansible using debug or set fact module

Time:12-15

I have following 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

 - 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:

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. 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

CodePudding user response:

One way to achieve this, would be to set_fact with when condition.

In the below example, we create a new variable serv_list (initially empty list), then append the DESCRIP and PORT when the criteria matches.

    - 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"
        }
    ]
}
  • Related