How to set dynamic values with Kubernetes yaml file

前端 未结 13 1936
旧巷少年郎
旧巷少年郎 2020-12-04 16:22

For example, a deployment yaml file:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: guestbook
spec:
  replicas: 2
  template:
    metadata         


        
相关标签:
13条回答
  • 2020-12-04 16:53

    If you just want to change the image or a tag while your deployment is running, you could set the image of a specific container in your deployment:

    kubectl apply -f k8s
    kubectl set image deployments/worker-deployment worker=IMAGE:TAG
    
    0 讨论(0)
  • 2020-12-04 16:54

    I create a script called kubectl_apply. It loads variables from .env, replace ${CUSTOMVAR} in yml and pass it to kubectl command

      #!/bin/bash
      set -a
      source .env
      set +a
      eval "cat <<EOF
      $(<$1)
      EOF
      " | kubectl apply -f -
    
    0 讨论(0)
  • 2020-12-04 16:58

    You can't do it automatically, you need to use an external script to "compile" your template, or use helm as suggested by @Jakub.

    You may want to use a custom bash script, maybe integrated with your CI pipeline.

    Given a template yml file called deploy.yml.template very similar to the one you provided, you can use something like this:

    #!/bin/bash
    
    # sample value for your variables
    MYVARVALUE="nginx:latest"
    
    # read the yml template from a file and substitute the string 
    # {{MYVARNAME}} with the value of the MYVARVALUE variable
    template=`cat "deploy.yml.template" | sed "s/{{MYVARNAME}}/$MYVARVALUE/g"`
    
    # apply the yml with the substituted value
    echo "$template" | kubectl apply -f -
    
    0 讨论(0)
  • 2020-12-04 17:01

    I have been using kubetpl

    It has three different template flavors and supports ConfigMap/Secret freezing.

    0 讨论(0)
  • 2020-12-04 17:04

    You can also use envsubst when deploying.

    e.g.

    cat $app/deployment.yaml | envsubst | kubectl apply ...
    

    It will replace all variables in the file with their values. We are successfully using this approach on our CI when deploying to multiple environments, also to inject the CI_TAG etc into the deployments.

    0 讨论(0)
  • 2020-12-04 17:05

    I've published a command-line tool ysed that helps exactly with that, in case you plan to script it.

    0 讨论(0)
提交回复
热议问题