Jenkins Declarative Pipeline 구성 및 K8s Agent 연동 가이드

Jenkins Plugin 설치 Jenkins 에서 제공하는 기본 플러그인 외에 추가로 필요한 플러그인 설치 Jenkins > 플러그인 관리 > 설치 가능 탭에서 필요한 플러그인 검색 Kubernetes Github Gitlab Blue Ocean (Optional) 설치가 완료되면 Jenkins 재시작 Jenkins Kubernetes Credential 설정 Jenkins > 관리 > Credentials > Global credentials (unrestricted) > Add Credentials Kind: Secret file File: ~/.kube/config ID: kube-config Description: Kubernetes config file Jenkins Kubernetes Cloud 설정 Jenkins > 관리 > Cloud > Kubernetes Cloud Details Kubernetes URL: https://kubernetes.default Kubernetes Namespace: jenkins Credentials: kube-config Jenkins Gitlab Credential 설정 Jenkins > 관리 > Credentials > Global credentials (unrestricted) > Add Credentials Kind: Username with password Username: gitlab username (gitlab 에서 사용하는 username) Password: gitlab password (gitlab 에서 사용하는 password) ID: gitlab-credential Description: Gitlab credential Jenkinsfile 작성 // Jenkins Pipeline 예시 // Test app 을 Docker build 하고 Git push 하는 파이프라인 pipeline { agent { // kubernetes 에서 실행 kubernetes { yaml ''' apiVersion: v1 kind: Pod spec: containers: - name: python image: python:3.10 command: - cat tty: true - name: kaniko image: gcr.io/kaniko-project/executor:debug command: - cat tty: true volumeMounts: - name: registry-credentials mountPath: /kaniko/.docker volumes: - name: registry-credentials secret: secretName: regcred items: - key: .dockerconfigjson path: config.json''' } } stages { // Unit Test (테스트를 위해 python 컨테이너에서 실행) // Test 결과가 성공이면 Docker Build 수행 // 테스트를 위해 적용한 스테이지로 필수로 포함할 필요는 없음 stage('Test') { steps { container('python') { sh 'pip install -r requirements.txt' sh 'python test_app.py' } } } // Docker Build // kaniko 컨테이너에서 Dockerfile 을 통해 이미지 빌드 // 컨테이너 내부에서 Docker 빌드를 위해 [kaniko](https://github.com/GoogleContainerTools/kaniko) 를 사용 // Docker build 후 Docker Hub 에 Push stage('Docker Build') { steps { container('kaniko') { sh "executor --dockerfile=Dockerfile \ --context=dir://${env.WORKSPACE} \ --destination=<docker-id>/test-app:${currentBuild.number}" } } } // docker image 를 deployment.yaml 에 적용 // deployment.yaml 의 image version 을 현재 빌드 번호로 변경 // 변경된 deployment.yaml 을 git 에 push stage('Modified deployment.yaml') { steps { sh "sed -i 's/test-app:.*\$/test-app:${currentBuild.number}/g' deployment.yaml" withCredentials([gitUsernamePassword(credentialsId: 'gitlab-credential', gitToolName: 'git-tool')]) { sh 'git checkout main' sh 'git fetch --all' sh 'git add deployment.yaml' sh "git commit -m 'Update image version test-app:${currentBuild.number} in deployment.yaml'" sh 'git push -u origin main' } } post { success { echo 'Deploy Success' } failure { echo 'Deploy Failure' } } } } } Jenkins Pipeline 실행 Jenkins > 새로운 Item > Enter an item name: test-app Pipeline 선택 > OK Pipeline > Definition: Pipeline script from SCM SCM: Git Repository URL: 대상 gitlab repository 주소 Credentials: Gitlab credential Branches to build: main Script Path: Jenkinsfile 저장 후 빌드 실행 Jenkins Pipeline 결과 확인 Jenkins Pipeline 실행 결과 확인 오류 발생 시 Console Output 확인 정상적으로 빌드가 완료되면 Gitlab 에서 변경된 deployment.yaml 확인 ArgoCD 에서 변경된 deployment.yaml 을 통해 배포 확인

June 7, 2023 · 3 min

Kubernetes 환경에서 Jenkins 설치 및 기본 설정 가이드

Jenkins Kubernetes 설치 준비 Namespace 생성 # jenkins namespace 생성 kubectl create namespace jenkins Persistent Volume, Persistent Volume Claim 생성 (Optional) 아래 예시는 특정 노드의 local path를 사용하는 정적 프로비저닝(static provisioning) 예시이므로, ebme-storage와 동일한 이름의 StorageClass가 클러스터에 미리 존재해야 하며 PV가 바인딩될 노드(kube-cluster-worker1)도 실제 환경에 맞게 수정 필요 # jenkins-pvc.yaml # ebme-storage class 를 사용하는 30Gi 크기의 PV, PVC 생성 apiVersion: v1 kind: PersistentVolume metadata: name: jenkins-pv spec: capacity: storage: 30Gi accessModes: - ReadWriteOnce persistentVolumeReclaimPolicy: Retain storageClassName: ebme-storage local: path: /mnt/jenkins nodeAffinity: required: nodeSelectorTerms: - matchExpressions: - key: kubernetes.io/hostname operator: In values: - kube-cluster-worker1 --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: jenkins-pvc namespace: jenkins spec: accessModes: - ReadWriteOnce storageClassName: ebme-storage resources: requests: storage: 30Gi Jenkins Service Account 생성 (Optional) # jenkins-service-account.yaml # In GKE need to get RBAC permissions first with # kubectl create clusterrolebinding cluster-admin-binding --clusterrole=cluster-admin [--user=<user-name>|--group=<group-name>] --- apiVersion: v1 kind: ServiceAccount metadata: name: jenkins --- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: jenkins rules: - apiGroups: [""] resources: ["pods"] verbs: ["create","delete","get","list","patch","update","watch"] - apiGroups: [""] resources: ["pods/exec"] verbs: ["create","delete","get","list","patch","update","watch"] - apiGroups: [""] resources: ["pods/log"] verbs: ["get","list","watch"] - apiGroups: [""] resources: ["events"] verbs: ["watch"] - apiGroups: [""] resources: ["secrets"] verbs: ["get"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: jenkins roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: jenkins subjects: - kind: ServiceAccount name: jenkins Jenkins values.yaml 생성 (Optional) Jenkins 에서 제공하는 기본 템플릿 value.yaml 에서 필요한 부분만 수정 # jenkins-values.yaml # persistence 부분을 아래와 같이 수정 persistence: enabled: true existingClaim: "jenkins-pvc" storageClass: "ebme-storage" accessMode: "ReadWriteOnce" size: "30Gi" Helm을 사용한 젠킨스 설치 Jenkins Repository 추가 helm repo add jenkinsci https://charts.jenkins.io helm repo update Jenkins 설치 # 기본 설정대로 설치 helm install -n jenkins jenkins jenkinsci/jenkins # 기존 작성한 jenkins-values.yaml 을 사용하여 설치 helm install -n jenkins jenkins jenkinsci/jenkins -f jenkins-values.yaml Jenkins Service expose NodePort 로 Service 를 expose 하여 접속 가능하도록 설정 해당 주소로 Jenkins 접속 확인 kubectl expose svc jenkins -n jenkins --type=NodePort --name=jenkins Jenkins 비밀번호 확인 kubectl exec --namespace jenkins -it svc/jenkins -c jenkins -- /bin/cat /run/secrets/chart-admin-password && echo

June 7, 2023 · 2 min