1

Hi, Could someone please help how to sort the below using ansible

"msg": [
    {
        "Desc": "jkl - txt to search-\n",
        "SCTASK": "SCTASK000001"
    },
    {
        "Desc": "xyz - txt to search-\n",
        "SCTASK": "SCTASK000002"
    },
    {
        "Desc": "def - txt to search-\n",
        "SCTASK": "SCTASK000003"
    },
    {
        "Desc": "def - txt to search-\n",
        "SCTASK": "SCTASK000004"
    },
    {
        "Desc": "abc- txt to search-\n",
        "SCTASK": "SCTASK000005"
    }
  ]

I need to get both sctask and description where 'abc' word present in 'Desc'. I tried to use where condition in my code block but it's not filtering.

- set_fact:
    SCT: "{{ jsoncontent.json | json_query(query)}}"
  vars:
    query: "result[*].{Desc: description, SCTASK: number}"

- name: debug
  debug: msg="{{ item }}"
  loop: "{{SCT}}"
  when: SCT is search("abc")

   

Thanks!

1 Answer 1

2

Q: "Get both sctask and description where 'abc' word present in 'Desc'."

A: json_query is not needed. Simply use the filter selectattr

    - set_fact:
        SCT: "{{ jsoncontent.json.result|selectattr('Desc', 'search', 'abc') }}"

gives

SCT:
  - Desc: |-
      abc- txt to search-
    SCTASK: SCTASK000005

Notes

  • If you want to select the items in the loop simply iterate the list
    - debug:
        msg: "{{ item }}"
      loop: "{{ jsoncontent.json.result }}"
      when: item.Desc is search("abc")

gives

TASK [debug] *******************************************************************************
skipping: [localhost] => (item={'Desc': 'jkl - txt to search-\n', 'SCTASK': 'SCTASK000001'}) 
skipping: [localhost] => (item={'Desc': 'xyz - txt to search-\n', 'SCTASK': 'SCTASK000002'}) 
skipping: [localhost] => (item={'Desc': 'def - txt to search-\n', 'SCTASK': 'SCTASK000003'}) 
skipping: [localhost] => (item={'Desc': 'def - txt to search-\n', 'SCTASK': 'SCTASK000004'}) 
ok: [localhost] => (item={'Desc': 'abc- txt to search-\n', 'SCTASK': 'SCTASK000005'}) => 
  msg:
    Desc: |-
      abc- txt to search-
    SCTASK: SCTASK000005
  • You can also create the list SCT in a loop. The task below gives the same result.
    - set_fact:
        SCT: "{{ SCT|d([]) + [item] }}"
      loop: "{{ jsoncontent.json.result }}"
      when: item.Desc is search("abc")
Sign up to request clarification or add additional context in comments.

2 Comments

Can we pass the variable too to selecattr ? I tried the following but seems its picking only one variable. code contain abc and xyz - name: set variable set_fact: SCT "{{ jsoncontent.json.result | selectattr('Desc', 'contains', item.d ) }}" with_items: "{{code}}"
Sure. What's preventing you from trying?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.