【问题标题】:How to fetch certain value from Dictionary in ansible如何在ansible中从字典中获取某些值
【发布时间】:2022-01-13 22:54:26
【问题描述】:

这是我的字典列表

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

如果列表有 displayName = video_dataset,我正在尝试从“name”键中获取第 5 个元素。

所以这里的输出是 123456789。

这是我的 ansible 脚本,其中一种方法是使用 json_query:

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

这给了我错误的说法,

Undefine Variable : 'displayName'

我尝试了几种方法,但没有运气。任何建议都会很重要。

提前致谢。

【问题讨论】:

  • {{ json.datasets | selectattr('display_name', '==', 'video_dataset') | map(attribute='name') | map('regex_replace', '^.*/(\\d*)$', '\\1') }}。就地写在我的手机上,未经测试。

标签: json list dictionary ansible


【解决方案1】:

JmesPath 中没有 split 功能。您可以映射 Ansible filter。例如

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

给予

  dataset_ID:
  - '123456789'

【讨论】:

  • 感谢您的回答。有用。但是 dataset_ID 作为列表中的对象出现。关于如何将其作为正常输出 '123456789' 而不是像 ['123456789'] 这样的列表中的对象的任何想法。再次感谢。
  • dataset_ID 是一个列表,因为可能有更多符合条件的 datasets。如果需要,只需从列表中选择第一项 "{{ dataset_ID.0 }}"
  • 这就是我要找的:{{ json.datasets | json_query(查询) |地图('拆分','/')|地图(属性=5)|列表 |第一个}}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
  • 2017-01-31
  • 2020-03-24
  • 2021-07-16
  • 1970-01-01
相关资源
最近更新 更多