Home > Software engineering >  How do I pass a variable to a kubectl deployment?
How do I pass a variable to a kubectl deployment?

Time:05-20

I am trying to make quick tweaks to the compute requests for a large number of deployments rather than having to get a PR approved if it turns out we need to change the numbers slightly. I need to be able to pass just one variable to the yaml file that gets applied.

Example below.

Shell Script:

#!/bin/bash

APPCENTER=(pa nyc co nc md sc mi)
for ac in "${APPCENTER[@]}"
do
  kubectl apply -f jobs-reqtweaks.yaml --env=APPCENTER=$ac
  kubectl apply -f queue-reqtweaks.yaml --env=APPCENTER=$ac
  kubectl apply -f web-reqtweaks.yaml --env=APPCENTER=$ac
done

YAML deployment file:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: example-app
    app.kubernetes.io/managed-by: Helm
    appcenter: $APPCENTER
    chart: example-app-0.1.0
    component: deployment-name
    heritage: Tiller
    release: example-app-fb-feature-tp-1121-fb-pod-resizing
  name: $APPCENTER-deployment-name
  namespace: example-app-fb-feature-tp-1121-fb-pod-resizing
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: example-app
      appcenter: $APPCENTER
      chart: example-app-0.1.0
      component: deployment-name
      heritage: Tiller
      release: example-app-fb-feature-tp-1121-fb-pod-resizing
  template:
    metadata:
      labels:
        app: example-app
        appcenter: $APPCENTER
        chart: example-app-0.1.0
        component: deployment-name
        heritage: Tiller
        release: example-app-fb-feature-tp-1121-fb-pod-resizing
    spec:
      containers:
        name: deployment-name
        resources:
          limits:
            memory: "400Mi"
            cpu: "10m"
          requests:
            cpu: 11m
            memory: 641Mi

CodePudding user response:

kubectl apply doesn't accept an --env flag (kubectl apply --help).

You have various choices:

  1. sed -- treats the YAML as a text file
  2. yq -- treats YAML as YAML
APPCENTER=(pa nyc co nc md sc mi)
for ac in "${APPCENTER[@]}"
do
  for FILE in "a" "b" "c"
  do
    # Either
    sed \
    --expression="s|\$APPCENTER|${ac}|g" \
    ${FILE}| kubectl apply --filename=-
    # Or
    UPDATE="with(select(documentIndex==0)
    ; .metadata.labels.appcenter=\"${ac}\"
    | .spec.selector.matchLabels.appcenter=\"${ac}\"
    | .spec.template.metadata.labels.appcenter=\"${ac}\"
    )"
    yq eval "${UPDATE}" \
    ${FILE}| kubectl apply --filename=-
  done
done

CodePudding user response:

Your script can use envsubst and be effective:

#!/bin/bash

AC=(pa nyc co nc md sc mi)
for APPCENTER in "${AC[@]}"
do
  envsubst '$APPCENTER' < jobs-reqtweaks.yaml | kubectl apply -f - 
  envsubst '$APPCENTER' < queue-reqtweaks.yaml | kubectl apply -f - 
  envsubst '$APPCENTER' < web-reqtweaks.yaml | kubectl apply -f -
done
  • Related