본문 바로가기

개발일지/TIL

[230717] [미니] 모여봐요 인생네컷 CI/CD 구성 (3)

Git Web Hook 설정

💬 Git Repositroy에 이벤트가 발생 시 Jenkins으로 메시지를 보내기 위해 설정

 

1.Git Webhooks 설정 페이지로 이동
Git Repository Of Application -> Settings -> Code and automation -> Webhooks -> Add webhook

2.Git Webhooks 설정
Payload URL: https://Jenkins domain:Jenkins port/github-webhook/
Content Type : application/json
Which events... this webhook? : Just the push event select
Active Check

3.Git Webhooks 생성

Spring Project에 JenkinsFile 추가

💬 Jenkins에서 실행되어야 하는 명령어를 설정

 

1.Project 최상단에 Jenkinsfile 생성

2.Jekinsfile에 생성해야 하는 명령어 입력
pipeline {
    agent any

    environment {
        registry = "도커 이미지 저장소"
        registryCredential = 'dockerhub'
        dockerImage = ''
    }

    stages {
        stage('Prepare') {
          steps {
            echo 'Clonning Repository'
            git url: 'Git SSH URL',
              branch: 'main',
              credentialsId: 'github'
            }
            post {
             success { 
              echo 'Successfully Cloned Repository'
             }
          	 failure {
              error 'This pipeline stops here...'
             }
          }
        }

        stage('Bulid Gradle') {
          steps {
            echo 'Bulid Gradle'
            dir('.'){
                sh 'chmod +x gradlew'
                sh './gradlew clean build'
            }
          }
          post {
            failure {
              error 'This pipeline stops here...'
            }
          }
        }
        
        stage('Bulid Docker') {
          steps {
            echo 'Bulid Docker'
            script {
                dockerImage = docker.build registry
            }
          }
          post {
            failure {
              error 'This pipeline stops here...'
            }
          }
        }

        stage('Push Docker') {
          steps {
            echo 'Push Docker'
            script {
                docker.withRegistry( 'https://registry.hub.docker.com', registryCredential ) {
                    dockerImage.push()
                }
            }
          }
          post {
            failure {
              error 'This pipeline stops here...'
            }
          }
        }
        
        stage('Docker Run') {
            steps {
                echo 'Pull Docker Image & Docker Image Run'
                sshagent (credentials: ['ssh']) {
                    sh "ssh -o StrictHostKeyChecking=no 서버 IP  'docker pull 도커 이미지'"
                    sh "ssh -o StrictHostKeyChecking=no 서버 IP 'docker ps -q --filter 'name=이미지 이름' | grep -q . && docker stop 이미지 이름 && docker rm -fv 이미지 이름 || [ \$? = 1 ]'"
                    sh "ssh -o StrictHostKeyChecking=no 서버 IP 'docker run -d --name four-cut -p 8080:8080 도커 이미지'"
                }
            }
        }
    }
}

Jenkins 결과

생각

Git WebHook과 Jenkinsfile을 만드는 것은 앞에 했던 것들보다 쉬웠다. 무난하게 진행이 되어 한시름 놓을 수 있었던 것 같다. 이렇게 전부 하고 보니 진짜 편리하긴 했다. 그런데 만드는 과정이 너무 험난하다. 이게 맞는 거겠지??