<p><strong>I have the following json</strong></p>

<pre><code>{
    "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"
                            },
                        ]
                    }
                ]
            }
        }
    }
}
</code></pre>

<p><strong>How do I add <code>deployment_env.json</code> using jsonnet?</strong></p>

<pre><code>{
    "env": [
        {
            "name":"GF_AUTH_DISABLE_LOGIN_FORM",
            "value":"false"
        },
        {
            "name":"GF_AUTH_BASIC_ENABLED",
            "value":"false"
        },

    ]
}
</code></pre>

<p>I need to add it under spec.template.containers[0].env = deployment_env.json</p>

<p>I wrote the below jsonnet to do that. It appends a new element. But i need to change the existing 0th container element in the json. <strong>Please suggest how to do it.</strong></p>

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

<p>See below for an implementation that allows adding <code>env</code> to an existing container by its index in the <code>containers[]</code> array.</p>

<p>Do note that <code>jsonnet</code> is much better suited to work with objects (i.e. dictionaries / maps) rather than arrays, thus it needs contrived handling via <code>std.mapWithIndex()</code>, to be able to modify an entry from its matching index.</p>

<pre><code>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 
</code></pre>
