Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to patch container env variable in deployment with kubectl?

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?

like image 731
lexadler Avatar asked Sep 05 '19 07:09

lexadler


People also ask

How do I update environment variables in Kubernetes?

When you create a Pod, you can set environment variables for the containers that run in the Pod. To set environment variables, include the env or envFrom field in the configuration file. In your shell, run the printenv command to list the environment variables. To exit the shell, enter exit .

How do I set an environment variable in Kubernetes deployment?

Define an environment variable for a container To set environment variables, include the env or envFrom field in the configuration file. Note: The environment variables set using the env or envFrom field override any environment variables specified in the container image.

What is kubectl patch command?

The kubectl patch command takes YAML or JSON. It can take the patch as a file or directly on the command line. Create a file named patch-file.json that has this content: { "spec": { "template": { "spec": { "containers": [ { "name": "patch-demo-ctr-2", "image": "redis" } ] } } } }


1 Answers

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.

like image 91
mchawre Avatar answered Nov 08 '22 19:11

mchawre