프로그래밍 언어/Jenkins

젠킨스 파이프라인 구축 및 SVN 구성 예시

해달이랑 2024. 5. 20. 23:53

Jenkins 파이프라인 구축

목차

  1. Jenkins 설치 및 플러그인 설정
  2. Jenkins 파이프라인 구성
  3. SVN 설정
  4. 환경 변수 설정
  5. 파이프라인 단계 구성
    • Checkout SVN
    • Update SVN
    • Get SVN Info
    • Process SVN Paths
    • Create ZIP Archive
  6. 이메일 알림 설정

1. Jenkins 설치 및 플러그인 설정

Jenkins 설치

Jenkins를 설치하기 위해 Jenkins 공식 웹사이트에서 설치 파일을 다운로드하고 설치합니다.

필수 플러그인 설치

Jenkins를 설치한 후, 다음과 같은 플러그인을 설치해야 합니다:

  • Pipeline Utility Steps: ZIP 파일 생성 및 기타 유틸리티 기능 제공.
  • Email Extension Plugin: 이메일 알림 기능 제공.
  • Subversion Plugin: SVN 지원.

플러그인 설치 방법:

  1. Jenkins 웹 인터페이스에 로그인합니다.
  2. 왼쪽 메뉴에서 "Manage Jenkins"를 클릭합니다.
  3. "Manage Plugins"를 클릭합니다.
  4. "Available" 탭에서 필요한 플러그인을 검색하여 설치합니다.

2. Jenkins 파이프라인 구성

새 파이프라인 생성

  1. Jenkins 웹 인터페이스에서 "New Item"을 클릭합니다.
  2. "Pipeline"을 선택하고 이름을 입력한 후 "OK"를 클릭합니다.

3. SVN 설정

SVN 저장소를 체크아웃하고 최신 상태로 유지합니다. 필요한 경우, Jenkins에 SVN 자격 증명을 설정합니다.

  1. Jenkins의 "Credentials" 섹션에서 SVN 자격 증명을 추가합니다.
  2. 파이프라인 스크립트에서 SVN 자격 증명 ID를 사용하여 체크아웃합니다.

4. 환경 변수 설정

파이프라인 전체에서 사용할 환경 변수를 설정합니다.

environment {
    SVN_URL = 'https://your-svn-repo-url/path/to/your/project'
    SVN_CREDENTIALS_ID = 'your-svn-credentials-id'
    SOURCE_DIR = 'path/to/source/directory'
    ZIP_FILE = 'path/to/destination/archive.zip'
    LOCAL_DIR = 'C:\\path\\to\\your\\local\\working\\directory'
    DATE_FORMAT = 'yyyyMMdd-HHmmss'
    SMTP_SERVER = 'smtp.yourserver.com'
    SMTP_PORT = '587'
    SMTP_USER = 'your-email@yourserver.com'
    SMTP_PASSWORD = 'your-email-password'
    RECIPIENTS = 'recipient@example.com'
    SUBJECT = 'Jenkins Pipeline Build Notification'
}

5. 파이프라인 단계 구성

 

Checkout SVN

SVN 리포지토리를 체크아웃합니다.

stage('Checkout SVN') {
    steps {
        checkout([$class: 'SubversionSCM',
                  locations: [[credentialsId: env.SVN_CREDENTIALS_ID,
                               remote: env.SVN_URL]]])
    }
}
 

Update SVN

작업 복사본을 최신 상태로 업데이트합니다.

stage('Update SVN') {
    steps {
        script {
            sh 'svn update'
        }
    }
}
 

Get SVN Info

현재 리비전을 가져와서 환경 변수에 저장합니다.

stage('Get SVN Info') {
    steps {
        script {
            def svnInfo = sh(script: 'svn info', returnStdout: true).trim()
            echo "SVN Info:\n${svnInfo}"
            def lastChangedRev = sh(script: 'svn info | grep "Last Changed Rev" | awk \'{print $4}\'', returnStdout: true).trim()
            echo "Last Changed Rev: ${lastChangedRev}"
        }
    }
}

Process SVN Paths

변경된 파일 목록을 처리하고, 필요한 디렉토리를 생성합니다.

stage('Process SVN Paths') {
    steps {
        script {
            def changedFiles = 'changed_files.txt'

            if (!fileExists(changedFiles)) {
                error "File ${changedFiles} not found!"
            }

            def lines = readFile(changedFiles).readLines()
            lines.each { line ->
                def parts = line.split(' ')
                def status = parts[0]
                def filePath = parts[1]

                def relativePath = filePath.replace(env.SVN_URL, '')
                def localFilePath = "${env.LOCAL_DIR}\\${relativePath}".replaceAll('/', '\\\\')

                def dirPath = localFilePath.substring(0, localFilePath.lastIndexOf('\\'))

                if (status != 'D') {
                    if (!fileExists(dirPath)) {
                        echo "Creating directory: ${dirPath}"
                        new File(dirPath).mkdirs()
                        if (!fileExists(dirPath)) {
                            error "Failed to create directory: ${dirPath}"
                        }
                    }
                }
            }
        }
    }
}

Create ZIP Archive

파일을 ZIP 형식으로 압축합니다.

stage('Create ZIP Archive') {
    steps {
        script {
            def zipFile = env.ZIP_FILE

            if (fileExists(zipFile)) {
                echo "Deleting existing ZIP file: ${zipFile}"
                sh "rm -f ${zipFile}"
            }

            echo "Creating ZIP archive: ${zipFile}"
            zip zipFile: zipFile, dir: env.SOURCE_DIR, archive: true
        }
    }
}

6. 이메일 알림 설정

빌드 결과를 이메일로 전송합니다.

post {
    always {
        script {
            emailext (
                subject: env.SUBJECT,
                body: "The Jenkins pipeline build has been completed.",
                to: env.RECIPIENTS,
                smtpHost: env.SMTP_SERVER,
                smtpPort: env.SMTP_PORT,
                replyTo: env.SMTP_USER,
                from: env.SMTP_USER,
                mimeType: 'text/plain',
                attachLog: true,
                compressLog: true,
                auth: true,
                username: env.SMTP_USER,
                password: env.SMTP_PASSWORD
            )
        }
    }
}