1. 키발급
github > Settings > Developer Settings > Personal access tokens > Tockens (classic) > Generate new token (classic)
2. webhook 설정
사용할 레포의 settings > Webhooks
3. 젠킨스에 webhooks 등록
다른 빌드에 있는 webhook은 풀어야함
Dashboard > Jenkins 관리 > Credentials > (Stores scoped to Jenkins 하단의 (global)) > Add Credentials
프로젝트 > 구성 > General
테스트
Readme에 아무거나 쓰고 commit 하면 자동으로 빌드
def deployApp(String targetServerIp) {
def jarPath = 'build/libs/파일명.jar'
def deployPath = '/home/ubuntu'
def runAppCommand = "nohup java -jar $deployPath/파일명.jar > nohup.log 2>&1 &"
def checkLogCommand = "grep -q 'Started CpuboundappApplication in' $deployPath/nohup.log"
def maxAttempts = 50
def checkInterval = 5
def currentAttempts = 0
def deployComplete = false
sshagent(['jenkins-ssh']) {
echo "Stopping previous deployment on ${targetServerIp}..."
sh "ssh -o StrictHostKeyChecking=no ubuntu@$targetServerIp 'ps -ef | grep java | grep -v grep | awk \"{print \\\$2}\" | sudo xargs kill -9 || echo \"No process found\"'"
echo "Transferring JAR file to ${targetServerIp}"
sh "scp -o StrictHostKeyChecking=no $jarPath ubuntu@$targetServerIp:$deployPath/"
echo "Starting application on ${targetServerIp}"
sh "ssh -o StrictHostKeyChecking=no ubuntu@$targetServerIp '${runAppCommand}'"
while (currentAttempts < maxAttempts) {
sleep checkInterval
def result = sh script: "ssh -o StrictHostKeyChecking=no ubuntu@$targetServerIp \"${checkLogCommand}\"", returnStatus: true
if (result == 0) {
echo "Deployment was successful on ${targetServerIp}."
deployComplete = true
break
}
currentAttempts++
}
if (!deployComplete) {
error "Deployment failed on ${targetServerIp}: Could not find 'Started CpuboundappApplication in' in log after ${maxAttempts} attempts."
}
}
}
pipeline {
agent any
environment {
GRADLE_HOME = tool 'GRADLE'
}
stages {
stage('Clone') {
steps {
git branch: 'main', url: 'https://github.com/깃주소.git'
}
}
stage('Build') {
steps {
sh "${GRADLE_HOME}/bin/gradle clean build"
sh 'ls build/libs'
}
}
stage('Deploy') {
steps {
script {
deployApp('인스턴스 1 비공인 IP')
}
}
}
stage('Deploy2') {
steps {
script {
deployApp('인스턴스 2 비공인 IP')
}
}
}
}
post {
success {
echo 'Pipeline completed successfully.'
}
failure {
echo 'Pipeline failed.'
}
}
}