【问题标题】:Ansible json_query'd json to yaml inventory with variablesAnsible json_query\'d json 到带有变量的 yaml 清单
【发布时间】:2023-02-07 06:04:26
【问题描述】:

我有一个可靠的 json_query'd 结果,我正试图将其用作另一本剧本的清单,但我缺乏处理数据的菜鸟技能。

json_query 是:

community.general.json_query('device_info.value[].{ hostname: DeviceName, serial: DeviceServiceTag, model: Model, connected: ConnectionState, networkaddress: DeviceManagement[0].NetworkAddress }')

结果是这样的(现实世界中有 100 多个主机):

[
  {
    "hostname": "thingy1.company.org",
    "serial": "serial1",
    "model": "modelA",
    "connected": true,
    "networkaddress": "1.2.3.4"
  },
  {
    "hostname": "thingy2.company.org",
    "serial": "serial2",
    "model": "modelB",
    "connected": true,
    "networkaddress": "1.2.3.5"
  }
]

我正在尝试将此结果转换为可用的 yaml 清单文件。这就是我想要达到的目的。

groupname:
  hosts:
    thingy1.company.org:
      connected: true
      model: modelA
      networkaddress: 1.2.3.4
      serial: serial1
    thingy2.company.org:
      connected: true
      model: modelB
      networkaddress: 1.2.3.5
      serial: serial2

有什么技巧可以帮助菜鸟吗?

【问题讨论】:

    标签: ansible yaml ansible-inventory jmespath


    【解决方案1】:

    给定清单

      result_list:
        - connected: true
          hostname: thingy1.company.org
          model: modelA
          networkaddress: 1.2.3.4
          serial: serial1
        - connected: true
          hostname: thingy2.company.org
          model: modelB
          networkaddress: 1.2.3.5
          serial: serial2
    

    声明字典

      result_dict: "{{ dict(result_list|map(attribute='hostname')|
                            zip(result_list)) }}"
    

      result_dict:
        thingy1.company.org:
          connected: true
          hostname: thingy1.company.org
          model: modelA
          networkaddress: 1.2.3.4
          serial: serial1
        thingy2.company.org:
          connected: true
          hostname: thingy2.company.org
          model: modelB
          networkaddress: 1.2.3.5
          serial: serial2
    

    您可以删除该属性主机名

      result_dict: "{{ dict(result_list|map(attribute='hostname')|
                            zip(result_list|
                                ansible.utils.remove_keys(target=['hostname']))) }}"
    

      result_dict:
        thingy1.company.org:
          connected: true
          model: modelA
          networkaddress: 1.2.3.4
          serial: serial1
        thingy2.company.org:
          connected: true
          model: modelB
          networkaddress: 1.2.3.5
          serial: serial2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 2020-11-27
      • 2023-03-25
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      相关资源
      最近更新 更多