Home > Enterprise >  How to fetch certain value from Dictionary in ansible
How to fetch certain value from Dictionary in ansible

Time:01-19

This is my list of dictionary

json:
    datasets:
    - createTime: '2020-01-10T18:18:29.010162Z'
      displayName: video_dataset
      name: projects/000111/locations/us-central1/datasets/123456789
    - createTime: '2020-01-10T18:18:29.010162Z'
      displayName: manual_dataset
      name: projects/000111/locations/us-central1/datasets/00556685
    - createTime: '2020-01-10T18:18:29.010162Z'
      displayName: wrong_dataset
      name: projects/000111/locations/us-central1/datasets/19967845

I am trying to fetch 5th element from "name" key if the list has displayName = video_dataset.

so the out put here would be 123456789.

Here is my ansible script and one of the method is using json_query:

- name: get dataset id
  set_fact : 
    dataset_ID: "{{ dataset_list.json.datasets | json_query([displayName=='video_dataset'].name.split('/')[5]) }}"

which gives me error saying,

Undefine Variable : 'displayName'

I tried several methods but no luck. Any advice would be appreciable.

Thanks in advance.

CodePudding user response:

There is no split function in JmesPath. You can map the Ansible filter instead. For example

    - set_fact:
        dataset_ID: "{{ json.datasets|json_query(query)|
                        map('split', '/')|map(attribute=5)|list }}"
      vars:
        query: "[?displayName == 'video_dataset'].name"

gives

  dataset_ID:
  - '123456789'
  •  Tags:  
  • Related