如何动态或使用变量在 Kubernetes 清单 deployment.yml 文件中定义图像名称?

How to define image name in Kubernetes manifest deployment.yml file dynamically or with variables?

我有 deplyonment.yml 文件,如下所示:

apiVersion : apps/v1
kind: Deployment
metadata:
  name: worker
spec:
  progressDeadlineSeconds: 3600
  replicas: 1
  selector:
    matchLabels:
      app: worker
  template:
    metadata:
      labels:
        app: worker
    spec:
      containers:
        - name: worker         
          image: $(RegistryName)/$(RepositoryName):$(Build.BuildNumber)
          imagePullPolicy: Always 

但我无法使用 $(RegistryName) 和 $(RepositoryName),因为我不确定如何初始化它并在此处赋值。

如果我指定如下内容

image: XXXX..azurecr.io/werepo:$(Build.BuildNumber)

它使用直接静态名称和确切名称。但我不想硬核注册表和存储库名称。

有什么办法可以动态替换这个吗?就像我在任务中传递这些的方式一样

  - task: KubernetesManifest@0
            displayName: Deploy to Kubernetes cluster
            inputs:
              action: deploy
              kubernetesServiceConnection: 'XXXX-connection'
              namespace: 'XXXX-namespace'
              manifests: |
                $(Pipeline.Workspace)/manifests/deployment.yml 
              containers: |
                $(Registry)/$(webRepository):$(Build.BuildNumber) 

你可以这样做

deployment.yaml

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: test-image
  labels:
    app: test-image
spec:
  selector:
    matchLabels:
      app: test-image
      tier: frontend
  strategy:
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: test-image
        tier: frontend
    spec:
      containers:
      - image: TEST_IMAGE_NAME
        name: test-image
        ports:
        - containerPort: 8080
          name: http
        - containerPort: 443
          name: https

在CI步骤或运行sed命令在ubuntu喜欢

steps:
- id: 'set test core image in yamls'
  name: 'ubuntu'
  args: ['bash','-c','sed -i "s,TEST_IMAGE_NAME,gcr.io/$PROJECT_ID/$REPO_NAME/$BRANCH_NAME:$SHORT_SHA," deployment.yaml']

以上将解决您的问题。

上面的命令只需找到并用创建 docker 图像 URI.

的变量替换 TEST_IMAGE_NAME

选项:2 kustomization

如果你想做自定义

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- service.yaml
- deployment.yaml
namespace: default
commonLabels:
  app: myapp
images:
- name: myapp
  newName: registry.gitlab.com/jkpl/kustomize-demo
  newTag: IMAGE_TAG

sh 文件

#!/usr/bin/env bash
set -euo pipefail

# Set the image tag if not set
if [ -z "${IMAGE_TAG:-}" ]; then
    IMAGE_TAG=$(git rev-parse HEAD)
fi

sed "s/IMAGE_TAG/${IMAGE_TAG}/g" k8s-base/kustomization.template.sed.yaml > location/kustomization.yaml

演示 github : https://gitlab.com/jkpl/kustomize-demo