如何将变量传递给 kubectl 部署?

How do I pass a variable to a kubectl deployment?

我正在尝试对大量部署的计算请求进行快速调整,而不是在事实证明我们需要稍微更改数字时必须获得 PR 批准。我需要能够将一个变量传递给应用的 yaml 文件。

示例如下。

Shell 脚本:

#!/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 部署文件:

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

kubectl apply 不接受 --env 标志 (kubectl apply --help)。

你有多种选择:

  1. sed -- 将 YAML 视为文本文件
  2. yq -- 将 YAML 视为 YAML

定义常数:

# The set of YAML files you want to change
FILES=(
  "jobs-reqtweaks.yaml"
  "queue-reqtweaks.yaml"
  "web-reqtweaks.yaml"
)

# The set of data-centers
APPCENTER=(pa nyc co nc md sc mi)

然后,要么使用 sed:

# Iterate over the data-centers
for ac in "${APPCENTER[@]}"
do
  # Iterate over the files
  for FILE in ${FILES[@]}
  do
    sed \
    --expression="s|$APPCENTER|${ac}|g" \
    ${FILE}| kubectl apply --filename=-
  done
done

或使用yq:

# Iterate over the data-centers
for ac in "${APPCENTER[@]}"
do
  # Iterate over the files
  for FILE in ${FILES[@]}
  do
    UPDATE="with(select(documentIndex==0)
    ; .metadata.labels.appcenter=\"${ac}\"
    | .metadata.name=\"${ac}-deployment-name\"
    | .spec.selector.matchLabels.appcenter=\"${ac}\"
    | .spec.template.metadata.labels.appcenter=\"${ac}\"
    )"
    yq eval "${UPDATE}" \
    ${FILE}| kubectl apply --filename=-
  done
done

您的脚本可以使用envsubst并且有效:

for i in pa nyc co nc md sc mi
do
  export APPCENTER=$i
  envsubst < your_sample_in_the_question.yaml | kubectl apply -f -
done

旁注:

...
spec:
 containers:
 - name: deployment-name
   resources:
     limits:
       memory: "400Mi"
       cpu: "10m"  # <-- This limit should be greater than requested.
     requests:
       cpu: 11m  # <-- ??
       memory: 641Mi