如何编写 kubernetes deployment 获取使用 GCP cloudbuild 构建的最新镜像

How to write kubernetes deployment to get the latest image built using GCP cloudbuild

我正在尝试使用 GCP cloudbuild 进行 CI/CD。

  1. 我在 GCP 中准备了一个 k8s 集群。检查下面的部署清单。
  2. 我有一个 cloudbuild.yaml 准备好构建新映像并将其推送到注册表和命令以更改部署映像。检查下面的 cloudbuild yaml。

以前,我曾经使用 TAG latest 为 docker 镜像推送镜像,并在部署中使用相同的标签,但它没有拉出最新的图像 所以现在我将其更改为使用 TAG $COMMIT_SHA。现在,我无法找到将基于 commit_sha 的带有 TAG 的新图像传递给部署的方法。

nginx-deployment.yaml

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: mynginx
spec:
  replicas: 3
  minReadySeconds: 50
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  selector:
    matchLabels:
      app: nginx

  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - image: gcr.io/foods-io/cloudbuildtest-image:latest
          name: nginx
          ports:
            - containerPort: 80

cloudbuild.yaml

steps:
  #step1      
- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build', '-t', 'gcr.io/$PROJECT_ID/cloudbuildtest-image:$COMMIT_SHA', '.' ]
  #step 2
- name: 'gcr.io/cloud-builders/docker'
  args: ['push', 'gcr.io/$PROJECT_ID/cloudbuildtest-image:$COMMIT_SHA']
  #STEP-3
- name: 'gcr.io/cloud-builders/kubectl'
  args: ['set', 'image', 'deployment/mynginx', 'nginx=gcr.io/foods-io/cloudbuildtest-image:$COMMIT_SHA']
  env:
  - 'CLOUDSDK_COMPUTE_ZONE=us-central1-a'
  - 'CLOUDSDK_CONTAINER_CLUSTER=cloudbuild-test'
images:
- 'gcr.io/$PROJECT_ID/cloudbuildtest-image'

Note: I repeat previously I was using the latest tag to the image and as is the same in deployment I expected to pull the new image with my 3rd steps in cloudbuild but that didn't so I made the above changes in TAG but now wondering how do I make changes to deployment manifest. Is using the helm only solution here?

您需要一个步骤来替换 deployment.yaml 中的标签,一种方法是使用环境变量并使用 envsubst 替换它。

更改deployment.yaml:

    - image: gcr.io/foods-io/cloudbuildtest-image:$COMMIT_SHA

使用一些bash脚本来替换变量(例如使用ubuntu step):

envsubst '$COMMIT_SHA' < deployment.yaml > nginx-deployment.yaml

替代使用sed

sed -e 's/$COMMIT_SHA/'"$COMMIT_SHA"'/g' deployment.yaml > /workspace/nginx-deployment.yaml