IT Infra
[Jenkins] 젠킨스를 이용한 CI과정
매료매료
2023. 8. 16. 10:29
* Jenkins 아이템 생성 시 2가지 방법이 있음
- 프리스타일
- 파이프라인
// 파이프라인 코드 예제
pipeline {
agent any
tools {
maven "Maven 3.6.3"
}
environment {
GIT_COMMIT_REV=''
GIT_CHANGE_BRANCH_NAME=''
GIT_COMMIT_SHA=''
}
options {
skipDefaultCheckout()
}
stages {
stage('git checkout & clone') {
steps {
script {
cleanWs()
GIT_CHANGE_BRANCH_NAME = sh(returnStdout: true, script: 'echo ${payload} | python3 -c \"import sys,json;print(json.load(sys.stdin,strict=False)[\'ref\'][11:])\"').trim()
GIT_COMMIT_SHA = sh(returnStdout: true, script: 'echo ${payload} | python3 -c \"import sys,json;print(json.load(sys.stdin,strict=False)[\'head_commit\'][\'id\'])\"').trim()
echo "arrive ${GIT_CHANGE_BRANCH_NAME}"
sh "git clone -b ${GIT_CHANGE_BRANCH_NAME} --single-branch \"https://github.com/{#계정명}/{#레포지토리명}.git\""
}
}
}
stage('Build') {
// maven compile, test, build
steps {
sh "mvn -f {#레포지토리명}/pom.xml -DskipTests clean package"
archiveArtifacts '{#레포지토리명}/target/*.jar'
}
// github api를 이용해 github으로 빌드&테스트 성공 실패 여부 전송
post {
success {
sh ("curl -X POST -H \"Content-Type: application/json\" \
--data '{\"state\": \"success\", \"context\": \"@@pass ci test & build\", \"target_url\": \"http://115.85.180.192:8080/job/{#레포지토리명}\"}' \
\"https://${GITHUB_TOKEN}@api.github.com/repos/{#계정명}/{#레포지토리명}/statuses/${GIT_COMMIT_SHA}\"")
}
failure {
sh ("curl -X POST -H \"Content-Type: application/json\" \
--data '{\"state\": \"failure\", \"context\": \"@@failure ci test & build\", \"target_url\": \"http://115.85.180.192:8080/job/{#레포지토리명}\"}' \
\"https://${GITHUB_TOKEN}@api.github.com/repos/{#계정명}/{#레포지토리명}/statuses/${GIT_COMMIT_SHA}\"")
}
}
}
stage('Dockerfile Build & Push To Docker Hub & Delete Docker Image') {
steps {
script {
sh "docker build -t {#ID}/{#레포지토리명} {#레포지토리명}/."
sh "docker push {#ID}/{#레포지토리명}"
sh "docker rmi {#ID}/{#레포지토리명}"
}
}
}
// 배포 서버로 빌드파일 전송
stage('Deploy') {
steps {
script {
sh "ssh -p {#포트번호} root@127.0.0.1 -T sh < /var/lib/jenkins/docker-deploy.sh"
}
}
}
}
}
1. Github에 수정된 코드가 push됨
2. Github는 1을 감지하고, Jenkins에 Github Webhook을 보냄
- GitHub(Gitlab) Webhook 설정 필요( 토큰 관련 )
- Webhook 은 repository 별로 설정해주어야 함.
3. Jenkins는 2를 감지하고, Webhook을 JSON 파일로 파싱
-
4. 파싱하여 변화된 branch를 파악하고 이 branch의 코드를 git clone
5. Jenkins 에서는 Maven 빌드, 컴파일, 테스트, 패키징 과정을 거쳐 빌드함.