使用ansible或jq合并2个json数组

问题描述 投票:0回答:1

所以我有2个json数组文件 一个包含一些简单数据的服务器(可以是任意数量的服务器):

    [
    {
    "playbook": "simplerun.yml",
    "server": "abc",
    "status": "success"
    },
    {
    "playbook": "simplerun.yml",
    "server": "def",
    "status": "success"
    }
    etc
    ]

和一个主文件(数十万台服务器),其中包含有关服务器的增强数据(但称为名称)

    [
    {
    "name": "abc",
    "fqdn": "abc.com",
    "env": "UAT",
    "ip_address": "0.0.0.0",
    "owner": "John Doe"
    },
    {
    "name": "def",
    "fqdn": "def.com",
    "env": "PROD",
    "ip_address": "0.0.0.1",
    "owner": "Jane Doe"
    }
    etc
    ]

我想要的是

    [
    {
    "playbook": "simplerun.yml",
    "server": "abc",
    "status": "success",
    "fqdn": "abc.com",
    "env": "UAT",
    "ip_address": "0.0.0.0",
    "owner": "John Doe"
    },
    {
    "playbook": "simplerun.yml",
    "server": "def",
    "status": "success",
    "fqdn": "def.com",
    "env": "PROD",
    "ip_address": "0.0.0.1",
    "owner": "Jane Doe"
    }
    ]

我知道这一定很简单,但是

非常感谢任何帮助。

我尝试过组合

     - name: set fact
       set_fact:
         key1: "server"
         key2: "name"
     
     - name: join data
       set_fact:
         joined_data: >- 
           {{ jsonfile1 | map ('combine',
              jsonfile2 |selectattr (key2,'eq', item[key1]|list|first|default ({}))
           }}
       loop: "{{ jsonfile1 }}"
       loop_control:
         loop_var: item

但是,这只为简单数据中的所有条目产生相同的值。

json merge ansible jq
1个回答
0
投票

您似乎正在寻找

JOIN

jq '[JOIN(input | INDEX(.name); .[]; .server; add)]' simple.json master.json
[
  {
    "playbook": "simplerun.yml",
    "server": "abc",
    "status": "success",
    "name": "abc",
    "fqdn": "abc.com",
    "env": "UAT",
    "ip_address": "0.0.0.0",
    "owner": "John Doe"
  },
  {
    "playbook": "simplerun.yml",
    "server": "def",
    "status": "success",
    "name": "def",
    "fqdn": "def.com",
    "env": "PROD",
    "ip_address": "0.0.0.1",
    "owner": "Jane Doe"
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.