728x90

 

 

지난번에 이어서, 

백엔드 앱 별로 젠킨스 CI 가 돌아갔을 때, 내 CD 를 잘 호출하는지를 확인해보자. 

 

groovy


pipeline {
    agent any

    stages {
        stage('Trigger Another Pipeline') {
            steps {
                // 다른 Job을 호출
                build job: 'another-pipeline-name', 
                      parameters: [string(name: 'PARAM1', value: 'value1')]
            }
        }
    }
}

 

 

 

이제 트리거 코드를 함 수정해줘보면 

        stage('Trigger CD Job') {
            steps {
                echo "IMAGE_TAG = v0.0.${env.BUILD_NUMBER}"
                echo "REGISTRY_ACCOUNT = ${params.REGISTRY_ACCOUNT}"
                echo "DOCKER_IMAGE = ${params.DOCKER_IMAGE}"
                
                build job: 'paperple-be-cd', 
                      parameters: [
                          string(name: 'IMAGE_TAG', value: "v0.0.${env.BUILD_NUMBER}"),
                          string(name: 'REGISTRY_ACCOUNT', value: "${params.REGISTRY_ACCOUNT}"),
                          string(name: 'DOCKER_IMAGE', value: "${params.DOCKER_IMAGE}")
                      ], 
                      wait: false
            }
        }

 

요런식으로 CI 에서 호출할거다

CD 코드도 수정해준다.


pipeline {
    agent any
    parameters {
            string(name: 'DOCKER_IMAGE', defaultValue: 'clpaas-test', description: 'Docker 이미지 이름')
            string(name: 'IMAGE_TAG', defaultValue: 'latest', description: 'Docker 이미지 태그')
            string(name: 'REGISTRY_ACCOUNT', defaultValue: 'pinetree0308', description: 'Docker 레지스트리 계정')
        }
    environment {
        gitlabURL = "https://gitlab.com"             // GitLab
        gitlabCredential = "gitlab-gitops-token"
        gitlabAccount = "cl-paas"
        gitlabProject = "clpaas-gitops"
        registryURLPull = "https://hub.docker.com/repository/docker"   // Docker registry URL
    }

    stages {
        stage('Clone Git Repository') {
            steps {
                script {
                    // GitLab에서 리포지토리 클론
                    withCredentials([usernamePassword(credentialsId: "$gitlabCredential",
                                                      usernameVariable: 'GITLAB_USER',
                                                      passwordVariable: 'GITLAB_ACCESS_TOKEN')]) {
                        sh """
                            git clone https://${GITLAB_USER}:${GITLAB_PASSWORD}@${gitlabURL}/${gitlabAccount}/${gitlabProject}.git
                        """
                    }
                }
            }
        }
        
        stage('Update Image Tag in Manifest') {
            steps {
                script {e
                    // Kustomize를 사용하여 이미지 태그 업데이트
                    dir(gitlabProject) {
                        sh """
                            cd ${params.DOCKER_IMAGE}/overlays/development
                            kustomize edit set image ${registryURLPull}/${params.REGISTRY_ACCOUNT}/${params.DOCKER_IMAGE}:${env.BUILD_ID}
                        """
                    }
                }
            }
        }

        stage('Push Changes to Git') {
            steps {
                script {
                    // 변경 사항을 Git에 커밋하고 푸시
                    withCredentials([usernamePassword(credentialsId: "$gitlabCredential",
                                                      usernameVariable: 'GITLAB_USER',
                                                      passwordVariable: 'GITLAB_ACCESS_TOKEN')]) {
                        sh """
                            cd ${gitlabProject}
                            git config --global user.email "clpaas@kt.co.kr"
                            git config --global user.name "Jenkins clpaas pipeline"
                            git add .
                            git commit -m "Update image tag to ${params.IMAGE_TAG}"
                            git push
                        """
                    }
                }
            }
        }
    }
}

 

그담에 deployment 파일을 똑같이 spring 관련 폴더에도 만들어준다.

 

 

 

이런식으로 만들어줬다.

 

일단 스프링 앱에서 파이프라인 호출은 잘된다.

 

다만,, 내 파이프라인이 깃랩 토큰 문제 이슈 발생

[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Update Image Tag in Manifest)
Stage "Update Image Tag in Manifest" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Push Changes to Git)
Stage "Push Changes to Git" skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: Credentials 'gitlab-gitops-token' is of type 'GitLab API token' where 'com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials' was expected
Finished: FAILURE

 

머 이거는 그냥 젠킨스 내부에서 깃랩 키를 api token 타입이 아니라 user&password 로 지정하라는 것,

다시 만들어줌

요런식으루

 

그래서 젠킨스 파이프라인 코드에도 저 ID 가 깃랩 크레덴셜 이름대신 들어감

 

오우 총 24번의 삽질 끝에 성공

삽질 과정 요약)

이 젠킨스가 돌아가고있는 컨테이너, 즉 파드 환경 내부에는 kustomize 가 안깔려있어서 설치했고,

kustomize 를 보통 설치 하면 /usr/bin~ 위치로 옮겨서 명령어로 사용가능한데,,

권한이 없어서 걍 절대경로로 지정해줌

 

그리고 git pull 을 받아주는.. 작업을 거침

 

 

최종 코드

pipeline {
    agent any
    parameters {
            string(name: 'DOCKER_IMAGE', defaultValue: 'clpaas-test', description: 'Docker 이미지 이름')
            string(name: 'IMAGE_TAG', defaultValue: 'latest', description: 'Docker 이미지 태그')
            string(name: 'REGISTRY_ACCOUNT', defaultValue: 'pinetree0308', description: 'Docker 레지스트리 계정')
        }
    environment {
        gitlabURL = "gitlab.com"             // GitLab
        gitlabCredential = "a8d7cfc2-2cf2-43ce-aa31-8a5334fe3dce"
        gitlabAccount = "cl-paas"
        gitlabProject = "clpaas-gitops"
        registryURLPull = "https://hub.docker.com/repository/docker"   // Docker registry URL
    }

    stages {
        stage('Clone or Pull Git Repository') {
            steps {
                script {
                    // GitLab에서 리포지토리 클론 또는 pull
                    withCredentials([usernamePassword(credentialsId: "$gitlabCredential",
                                                      usernameVariable: 'GITLAB_USER',
                                                      passwordVariable: 'GITLAB_ACCESS_TOKEN')]) {
                        sh """
                            if [ ! -d "${gitlabProject}" ]; then
                                git clone https://${GITLAB_USER}:${GITLAB_ACCESS_TOKEN}@${gitlabURL}/${gitlabAccount}/${gitlabProject}.git
                            else
                                cd ${gitlabProject}
                                git pull --rebase https://${GITLAB_USER}:${GITLAB_ACCESS_TOKEN}@${gitlabURL}/${gitlabAccount}/${gitlabProject}.git main
                            fi
                        """
                    }
                }
            }
        }
        // stage('Install Kustomize') {
        //     steps {
        //         script {
        //             sh '''
        //                 # Kustomize 다운로드
        //                 curl -sL https://github.com/kubernetes-sigs/kustomize/releases/latest/download/kustomize_v5.4.3_linux_amd64.tar.gz -o kustomize.tar.gz
        //                 chmod +x kustomize
        //                 ls -la                      # 현재 디렉토리의 파일 목록 확인
        //             '''
        //         }
        //     }
        // }

        stage('Update Image Tag in Manifest') {
            steps {
                script {
                    // Kustomize를 사용하여 이미지 태그 업데이트
                    dir(gitlabProject) {
                        sh """
                            ls -la
                            cd ${params.DOCKER_IMAGE}/overlay/dev
                            ls -la
                            ../../../../kustomize edit set image ${registryURLPull}/${params.REGISTRY_ACCOUNT}/${params.DOCKER_IMAGE}:${env.BUILD_ID}
                        """
                    }
                }
            }
        }

        stage('Push Changes to Git') {
            steps {
                script {
                    // 변경 사항을 Git에 커밋하고 푸시
                    withCredentials([usernamePassword(credentialsId: "$gitlabCredential",
                                                      usernameVariable: 'GITLAB_USER',
                                                      passwordVariable: 'GITLAB_ACCESS_TOKEN')]) {
                        sh """
                            cd ${gitlabProject}
                            git config --global user.email "clpaas@kt.co.kr"
                            git config --global user.name "Jenkins clpaas pipeline"
                            git add .
                            git commit -m "Update image tag to ${params.IMAGE_TAG}"
                            git push https://${GITLAB_USER}:${GITLAB_ACCESS_TOKEN}@${gitlabURL}/${gitlabAccount}/${gitlabProject}.git
                        """
                    }
                }
            }
        }
    }
}

 

아래와 같이 태그값을 patch.yaml 에 반영해줌

 

이제 이게 실제로 잘 돌아가고 있는가는 백엔드 어플리케이션 개발단의 에러가 해결되면 확인할 예정이다.

뿌듯~!

파드 제외하고는 다 잘 띄워진 모습

 

 

근데 sync 가 좀 늦는것같다. 이걸 해결할 방법 찾아야할듯!

 

[ 다음 해야할 작업 ]

- 남은 백엔드 2개어플리케이션 (nest, python 기반) 비슷한 과정으로 띄우기

- ingress 동작 확인  = > 프론트에서 ingress 접근 및 값 어떻게 주고받는지 확인

- 보고서 작성 

- 시간남으면 대시보드도 

 

728x90
리촬리