Jenkins free style과 다르게 Jenkins pipe line 에서 에서 GitHub 웹훅이 동작하려면 다음 플러그인들이 필요합니다

image.png

필수 플러그인:

# 해당 추가시 git webhook 인식

triggers {
    githubPush()  // push 이벤트
}

groovy file (파이프 스크립트 . no SCM )

// Jenkins 파이프라인 정의
// PR merge 이벤트와 수동 빌드를 모두 지원하는 빌드 파이프라인
pipeline {
    // 모든 Jenkins 에이전트에서 실행 가능
    agent any
    
    // 수동 빌드 시 사용할 파라미터 정의
    parameters {
        choice(
            name: 'SELECT_PROJECT',          // 파라미터 이름
            choices: ['smartq', 'cmng'],     // 선택 가능한 프로젝트 목록
            description: '빌드할 프로젝트 선택'  // 파라미터 설명
        )
    }

    // GitHub webhook 트리거 설정
    // PR merge 시 자동으로 빌드를 시작하기 위한 설정
    triggers {
        githubPush()
    }
    
    // 파이프라인 스테이지 정의
    stages {
        // Git 저장소 체크아웃 스테이지
        stage("Repository") {
            steps {
                script {
                    // 현재 빌드가 시작된 원인 확인
                    def cause = currentBuild.getBuildCauses()
                    echo "Build Causes: ${cause}"  // 빌드 원인 로깅
                    
                    // GitHub webhook에 의한 빌드인지 확인
                    def isWebhook = cause.toString().contains('GitHubPushCause')
                    echo "Is Webhook Build: ${isWebhook}"  // webhook 여부 로깅
                    
                    if (isWebhook) {
                        // webhook(PR merge)에 의한 자동 빌드 처리
                        echo "Webhook 빌드 시작"
                        
                        // git 명령어를 사용하여 현재 커밋의 브랜치 정보 가져오기
                        def branch = sh(
                            script: 'git ls-remote --heads origin | grep $(git rev-parse HEAD) | cut -d "/" -f 3-',
                            returnStdout: true
                        ).trim()
                        
                        echo "감지된 브랜치: ${branch}"  // 감지된 브랜치 정보 로깅
                        
                        // prod/smartq 또는 prod/cmng 브랜치인지 확인
                        if (branch.contains('prod/smartq') || branch.contains('prod/cmng')) {
                            // 해당 브랜치 체크아웃
                            git branch: branch,
                                credentialsId: 'cpt4567',  // GitHub 인증 정보
                                url: '<https://github.com/thankqcamping/thankq-monorepo.git>'
                        } else {
                            // 지원하지 않는 브랜치인 경우 에러 발생
                            error "지원하지 않는 브랜치입니다: ${branch}"
                        }
                    } else {
                        // 수동 빌드 처리
                        // 선택된 프로젝트에 따라 브랜치 결정
                        def branch = params.SELECT_PROJECT == 'smartq' ? 'prod/smartq' : 'prod/cmng'
                        echo "수동 빌드 - 선택된 브랜치: ${branch}"
                        
                        // 선택된 브랜치 체크아웃
                        git branch: branch,
                            credentialsId: 'cpt4567',
                            url: '<https://github.com/thankqcamping/thankq-monorepo.git>'
                    }
                    
                    // 체크아웃된 파일 목록 확인
                    sh 'ls -la'
                }
            }
        }

        // 프로젝트 의존성 설치 스테이지
        stage('Install Dependencies') {
            steps {
                script {
                    // node_modules 디렉토리 존재 여부 확인
                    def nodeModulesExists = fileExists 'node_modules'
                    if (!nodeModulesExists) {
                        echo "node_modules가 없습니다. 의존성 설치를 시작합니다..."
                        // pnpm을 사용하여 의존성 설치
                        sh 'pnpm install'
                    } else {
                        echo "node_modules가 이미 존재합니다."
                    }
                }
            }
        }
        
        // 프로젝트 빌드 스테이지
        stage('Build Project') {
            steps {
                script {
                    // 현재 체크아웃된 브랜치 확인
                    def currentBranch = sh(
                        script: 'git rev-parse --abbrev-ref HEAD',
                        returnStdout: true
                    ).trim()
                    
                    echo "빌드 대상 브랜치: ${currentBranch}"
                    
                    // 브랜치에 따라 적절한 빌드 명령 실행
                    if (currentBranch.contains('prod/smartq')) {
                        echo "Smart 프로젝트 빌드 시작"
                        sh 'pnpm build:smart'
                    } else if (currentBranch.contains('prod/cmng')) {
                        echo "Cmng 프로젝트 빌드 시작"
                        sh 'pnpm build:cmng'
                    } else {
                        error "지원하지 않는 브랜치입니다: ${currentBranch}"
                    }
                }
            }
        }
    }
    
    // 빌드 완료 후 실행되는 작업들
    post {
        // 빌드 성공 시 실행
        success {
            echo '빌드 성공!'
        }
        // 빌드 실패 시 실행
        failure {
            echo '빌드 실패!'
        }
        // 빌드 결과와 관계없이 항상 실행
        always {
            // 작업 공간 정리 (다음 빌드를 위해)
            cleanWs()
        }
    }
}