接續先前的文件用Google Cloud SDK 腳本指令部署 GKE,這次打算透過 Jenkins 實現自動化部署GKE。
在開始之前,請確保以下環境及資源已準備就緒:
依據官方教學安裝 Google Cloud CLI:參考 Google 官方文件 進行安裝。
登入 Google Cloud: 執行以下指令:
gcloud auth login --no-launch-browser
系統將生成一個驗證 URL(如下圖所示),可在其他可用瀏覽器的設備上完成登入操作。
進入 GCP 後台:
設定角色:
下載服務帳戶金鑰:
新增憑證:
注意:此處需要上傳兩份金鑰,分別用於:
withCredentials
使用。建立新 Pipeline:
GCP - Deploy to GKE
。撰寫 Pipeline 腳本: 以下為範例腳本:
properties([ pipelineTriggers([githubPush()]) ]) pipeline { agent any environment { TAG = ':latest' IMAGE_SHORT_NAME = 'k8s-next-ec' IMAGE_NAME = "${IMAGE_SHORT_NAME}${TAG}" CONTAINER_NAME = "${IMAGE_SHORT_NAME}-1" DOCKERFILE_PATH = './Dockerfile' REGISTRY_URL = 'asia-east1-docker.pkg.dev/careful-span-384313/my-registry' REGISTRY = "${REGISTRY_URL}/${IMAGE_SHORT_NAME}" GCP_PROJECT_ID = 'careful-span-384313' GIT_REPO_URL = '[email protected]:markku636/ec.git' GIT_BRANCH = 'main' GKE_CLUSTER_NAME = 'blog-autopilot-cluster' GKE_LOCATION = 'asia-east1' DEPLOYMENT_MANIFEST = './gc-next-js-deployment.yaml' } stages { stage('Authenticate with GCP') { steps { withCredentials([file(credentialsId: 'gke-ssh', variable: 'GCLOUD_CREDS')]) { sh ''' gcloud version gcloud auth activate-service-account --key-file="$GCLOUD_CREDS" gcloud config set project $GCP_PROJECT_ID gcloud auth configure-docker asia-east1-docker.pkg.dev ''' } } } stage("GitHub Pull") { steps { git branch: "${GIT_BRANCH}", credentialsId: 'e85233ad-a3c5-448b-a6ea-9f53e4f9b3f1', url: "${GIT_REPO_URL}" } } stage('Build Docker Image') { steps { sh "docker build -t ${IMAGE_NAME} -f ${DOCKERFILE_PATH} ." } } stage('Push to GCR') { steps { sh "docker tag ${IMAGE_NAME} ${REGISTRY}${TAG}" sh "docker push ${REGISTRY}${TAG}" } } stage("Cleaning Up") { steps { sh "docker rmi --force ${REGISTRY}${TAG}" } } stage('Deploy via GKE Plugin') { steps { step([ $class: 'KubernetesEngineBuilder', projectId: "${GCP_PROJECT_ID}", clusterName: "${GKE_CLUSTER_NAME}", location: "${GKE_LOCATION}", manifestPattern: "${DEPLOYMENT_MANIFEST}", credentialsId: 'gke-gsa', verifyDeployments: true ]) echo "Deployment Finished ..." } } } }
以下為 ./gc-next-js-deployment.yaml
範例內容:
apiVersion: apps/v1 kind: Deployment metadata: name: k8s-next-ec labels: app: k8s-next-ec spec: selector: matchLabels: app: k8s-next-ec tier: web template: metadata: labels: app: k8s-next-ec tier: web spec: containers: - name: k8s-next-ec-app image: asia-east1-docker.pkg.dev/careful-span-384313/my-registry/k8s-next-ec:latest imagePullPolicy: Always ports: - containerPort: 3000 --- apiVersion: v1 kind: Service metadata: name: k8s-next-ec labels: app: k8s-next-ec spec: selector: app: k8s-next-ec type: LoadBalancer ports: - name: http protocol: TCP port: 80 targetPort: 3000