Home > Software engineering >  Using env variable inside yaml deployment file in Kubernetes
Using env variable inside yaml deployment file in Kubernetes

Time:10-26

How do I use env variable defined inside deployment? For example, In yaml file dow below I try to use env CONT_NAME for setting container name, but it does not succeed. Could you help please with it, how to do it?

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: $CONT_NAME
        image: nginx:1.7.9
        env:
        - name: CONT_NAME
          value: nginx
        ports:
        - containerPort: 80

CodePudding user response:

You've created an environment variable inside the container. This has nothing to do with the container name. This variable can only be referenced inside your running container, not in your .yaml file.

If you just want to use a special name for your container, try this:

    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

CodePudding user response:

You can't use variables to set values inside deployment natively. If you want to do that you have to process the file before executing the kubectl, take a look at this post. The best option to do this which it's focused on parametrize and standardize deployments is to use Helm

CodePudding user response:

In those situations I just replace the $CONT_NAME in the yaml with the correct value right before applying the yaml.

sed -ie "s/\$COUNT_NAME/$COUNT_NAME/g" yourYamlFile.yaml

CodePudding user response:

If your using fluxcd, it has the ability to do variable interpolation link

  • Related