6

When I want to exctract the current value of some container env variabe I could use jsonpath with syntax like:

kubectl get pods -l component='somelabel' -n somenamespace -o \
jsonpath='{.items[*].spec.containers[*].env[?(@.name=="SOME_ENV_VARIABLE")].value}')

That will return me the value of env varialbe with the name SOME_ENV_VARIABLE. Pod section with container env variables in json will look like this:

            "spec": {
                "containers": [
                    {
                        "env": [
                            {
                                "name": "SOME_ENV_VARIABLE",
                                "value": "some_value"
                            },
                            {
                                "name": "ANOTHER_ENV_VARIABLE",
                                "value": "another_value"
                            }
                        ],

When I want to patch some value in my deployment I'm using commands with syntax like:

kubectl -n kube-system patch svc kubernetes-dashboard --type='json' -p="[{'op': 'replace', 'path': '/spec/ports/0/nodePort', 'value': $PORT}]"

But how can I patch a variable with 'op': 'replace' in cases where I need to use expression like env[?(@.name=="SOME_ENV_VARIABLE")]? Which syntax I should use?

lexadler
  • 245
  • 5
  • 13

3 Answers3

9

Rather than kubectl patch command, you can make use of kubectl set env to update environment variable of k8s deployment.

envvalue=$(kubectl get pods -l component='somelabel' -n somenamespace -o jsonpath='{.items[*].spec.containers[*].env[?(@.name=="SOME_ENV_VARIABLE")].value}')
kubectl set env deployment/my-app-deploy op=$envvalue

Hope this helps.

mchawre
  • 10,744
  • 4
  • 35
  • 57
1

Most of them haven't provide proper commands just use as simple as it is =>

kubectl set env deployment/deploy_name APP_VERSION=value -n namespace 
Kumar Pankaj Dubey
  • 1,541
  • 3
  • 17
  • 17
-2
  • op: replace path: /spec/template/spec/containers/0/env/0/name value: YOUR_VARIABLE_NAME
  • op: replace path: /spec/template/spec/containers/0/env/0/value value: YOUR_VARIABLE_VALUE
archcutbank
  • 419
  • 1
  • 6
  • 17
  • This just replaces the env item at index 0 rather than the item with the correct env var name. – Phil Mar 09 '22 at 23:04