บันทึก การใช้ gitlab ci deploy k8s

Aphichan Chaiyutthasart
Witsawa Corporation
2 min readMay 5, 2024

ขั้นตอนในการ ทำ gitlab ci เพื่อ deploy kubenetes ตามด้านล่างนี้

สร้าง agent สำหรับ connect k8s cluster

  • สร้าง agent ของ project ไปที่ Operate -> Kubenetes clusters กด Connect a cluster (agent) ใส่ชื่อ cluster แล้ว register จะได้ command ในการสร้าง pod
  • นำ command ที่เขา แนะนำ มา run
  • เมื่อดูใน gitlab connection status จะขึ้นว่า Connected

สร้าง credential สำหรับ pull image จาก gitlab registry

  • สร้าง deploy token ของ Group โดยไปที่เมนู Settings -> Repository -> Deploy tokens

สร้างเสร็จ จะได้ username password ไว้ เดี๋ยวไปสร้าง secret ต่อ

kubectl create secret docker-registry <secret-name> \
--namespace my-namespace \
--docker-server=registry.gitlab.com \
--docker-username=<username-in-deploy-token> \
--docker-password=<password-in-deploy-token> \
--dry-run=client -o yaml | kubectl apply -f -

ตัวอย่าง

kubectl create secret docker-registry gitlabci-registry-credential \
--namespace my-namespace \
--docker-server=registry.gitlab.com \
--docker-username=kube-prod \
--docker-password=AVAFDFDCAFDARfdafkljklfdjklaj \
--dry-run=client -o yaml | kubectl apply -f -

สร้าง script gitlab ci

# gitlab-ci.yml

image: docker:stable
services:
- name: docker:stable-dind
alias: docker

variables:
DOCKER_HOST: tcp://docker:2375
DOCKER_TLS_CERTDIR: ''
DOCKER_DRIVER: overlay2
DOCKER_IMAGE: ${CI_REGISTRY_IMAGE}
TAG: ${CI_COMMIT_REF_SLUG}

stages:
- build
- deploy

build-image-production:
before_script:
- sleep 30 && docker info
image: docker:stable
stage: build
script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- docker pull ${DOCKER_IMAGE}:$CI_COMMIT_REF_NAME || true
- docker build -t ${DOCKER_IMAGE}:$CI_COMMIT_REF_SLUG -f ./dockerfile .
- docker push ${DOCKER_IMAGE}:${TAG}
only:
- main

deploy-production:
stage: deploy
image: dtzar/helm-kubectl:3.11.0
environment:
name: production
url: https://api.example.com
variables:
NAME: myservice
HELM_PATH: ./myhelmchart
KUBE_CONTEXT: group/my-project:my-agent
K8S_PROXY_URL: https://kas.gitlab.com/k8s-proxy
before_script:
- kubectl config use-context "$KUBE_CONTEXT"
script:
- helm dependency update ${HELM_PATH}
- helm upgrade --install --force
--set image.pullPolicy=Always
--set image.repository="${DOCKER_IMAGE}"
--set image.tag="${TAG}"
--set imagePullSecrets[0].name=gitlabci-registry-credential
--wait
${NAME} ${HELM_PATH}
only:
- main

สร้าง script ตามด้านบน แล้วก็ push ขึ้น repo ได้เลย รอ build

  • ข้อควรระวัง namespace ของ secret docker-registry กับ ของ deployment ต้องชื่อเดียวกันนะ
  • ตัวอย่างเป็นการใช้ helm chart ต้องสร้างขึ้นมาก่อน เดี๋ยวไว้มาเขียนคราวหน้า ในเรื่องของการใช้ helm chart

วันนี้เท่านี้ก่อน ขอในสนุกกับการ deploy

--

--