由於近期更新了Synology NAS內所提供的Gitlab 版本從11 更新至13,
之前就有看到Gitlab 提供了 Kubernetes 的整合工具.
剛好手邊有申請一組在Linode上自己做測試的 Kubernetes cluster(LKE).
趁這個機會來嘗試一下Gitlab CI 與 Kubernetes 合體的感覺XD.
在此先說一聲無任何打廣告之行為.XD
以下是目前所採用的環境版本
GitLab Version : GitLab Community Edition 13.12.2
Linode Kubernetes Version : 1.21
macOS
接下來就是圖多嚕
首先先至Linode控制台下載kubeconfig至本機

請先在本機安裝kubectl 再透過kubectl取得所需的資訊
輸入下列指令將kubeconfig資訊匯入本機
export KUBECONFIG=$KUBECONFIG:$HOME/.kube/config:$HOME/Downloads/demo-kubeconfig.yaml
確認匯入的kubeconfig的context是否有加入
kubectl config get-contexts
由於我本身就有多個k8s cluster的所以顯示會呈現多個

指定欲操作的k8s cluster
kubectl config use-context lke36624-ctx
接下來我們先移至gitlab 內的 Repository 確認需要哪些資訊

點選Connect existing cluster

Kubernetes cluster name 可依照個人喜好隨意輸入.
API URL取得方式,透過kubectl輸入以下指令
kubectl cluster-info | grep -E 'Kubernetes master|Kubernetes control plane' | awk '/http/ {print $NF}'

CA Certificate 取得方式
先輸入
kubectl get secrets
確認格式是否為default-token-xxxxx

取得 CA Certificate
kubectl get secret default-token-g268k -o jsonpath="{['data']['ca\.crt']}" | base64 --decode

Service Token 取得方式
由於 token 是拿來跟K8s cluster 做驗證,
依照 gitlab 所說需要建立一個ServiceAccount 擁有cluster-admin權限
建立gitlab-admin-service-account.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: gitlab
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: gitlab-admin
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: gitlab
namespace: kube-system
執行
kubectl apply -f gitlab-admin-service-account.yaml

有點繞不過還是能取得Token嚕,輸入下列指令
kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep gitlab | awk '{print $1}')

接下來就把這些資訊當填空題,填一填嚕

確認k8s cluster是否有確實加入

透過 gitlab k8s Integration 安裝 GitLab Runner

點擊安裝.
安裝完成後我們透過kubectl 確認runner的狀況
kubectl get ns

安裝完成後預設會在namespace中建立gitlab-managed-apps
輸入以下指令確認runner是否有正確建立
kubectl get pod -n gitlab-managed-apps

看樣子runner確實有正確建立,
接下來測試看看我們的runner可否正常執行部署嚕
測試用部署檔 .gitlab-ci.yml
stages:
- imagebuild
- deploy
image_build:
stage: imagebuild
image: docker:stable
variables:
DOCKER_DRIVER: overlay
DOCKER_HOST: tcp://localhost:2375
DOCKER_TLS_CERTDIR: ""
services:
- name: docker:18.09.7-dind
script:
- docker version
deploy:
image: bitnami/kubectl:latest
stage: deploy
when: manual
script:
- kubectl version
dependencies:
- image_build
執行的過程中,如果去觀察gitlab-managed-apps pod 的內的行爲你會發現,
當Job執行時,會自動幫你產生pod

當Job結束時他會自動回收.
接下來看看所建立的 Stage是否有正確被執行

看到綠色勾勾就很開心,再來看看裡面的內容吧
imagebuild

deploy

確實都有正確的執行相對應的指令.
gitlab在整合上真的是越來越方便也越來越豐富XD .
參考連結:
Deploying and Managing a Cluster on Linode Kubernetes Engine (LKE)
Connect existing clusters through cluster certificates