使用jsonnet覆盖嵌套列表元素

使用jsonnet覆盖嵌套列表元素,json,kubernetes,prometheus,jsonnet,Json,Kubernetes,Prometheus,Jsonnet,我有以下json { "namespace": "monitoring", "name": "alok", "spec": { "replicas": 1, "template": { "metadata": "aaa", "spec": { "containers": [ {

我有以下json

{
    "namespace": "monitoring",
    "name": "alok",
    "spec": {
        "replicas": 1,
        "template": {
            "metadata": "aaa",
            "spec": {
                "containers": [
                    {
                        "image": "practodev/test:test",
                        "env": [
                            {
                                "name":"GF_SERVER_HTTP_PORT",
                                "value":"3000"
                            },
                            {
                                "name":"GF_SERVER_HTTPS_PORT",
                                "value":"443"
                            },
                        ]
                    }
                ]
            }
        }
    }
}
如何使用jsonnet添加
deployment\u env.json

{
    "env": [
        {
            "name":"GF_AUTH_DISABLE_LOGIN_FORM",
            "value":"false"
        },
        {
            "name":"GF_AUTH_BASIC_ENABLED",
            "value":"false"
        },

    ]
}
我需要将其添加到spec.template.containers[0].env=deployment\u env.json下

我写了下面的Jsonet来做这件事。它附加了一个新元素。但我需要更改json中现有的第0个容器元素请建议如何操作。

local grafana_envs = (import 'custom_grafana/deployment_env.json');
local grafanaDeployment = (import 'nested.json') + {
    spec+: {
        template+: {
            spec+: {
                containers+: [{
                    envs: grafana_envs.env,
                }]
            }
        }
    },
};
grafanaDeployment 

有关允许通过
containers[]
数组中的索引将
env
添加到现有容器的实现,请参见下文

请注意,
jsonnet
更适合使用对象(即字典/地图)而不是数组,因此它需要通过
std.mapWithIndex()
进行人为处理,才能从匹配索引中修改条目

local grafana_envs = (import 'deployment_env.json');

// Add extra_env to a container by its idx passed containers array
local override_env(containers, idx, extra_env) = (
  local f(i, x) = (
    if i == idx then x {env+: extra_env} else x
  );
  std.mapWithIndex(f, containers)
);
local grafanaDeployment = (import 'nested.json') + {
    spec+: {
        template+: {
            spec+: {
                containers: override_env(super.containers, 0, grafana_envs.env)
            }
        }
    },
};
grafanaDeployment 

替代实现,不依赖数组索引位置,而是
image
值(这在这里更有意义,因为镜像实现必须理解
env

local grafana_envs = (import 'deployment_env.json');

local TARGET_CONTAINER_IMAGE = 'practodev/test:test';

local grafanaDeployment = (import 'nested.json') + {
  spec+: {
    template+: {
      spec+: {
        containers: [
          // TARGET_CONTAINER_IMAGE identifies which container to modify
          if x.image == TARGET_CONTAINER_IMAGE
          then x { env+: grafana_envs.env }
          else x
          for x in super.containers
        ],
      },
    },
  },
};
grafanaDeployment