Gradle을 GRADLE로 변수를 짓는 느낌이라 Pipeline 코드에서는 GRADLE을 호출해야 함.
0.2 SSH agent 설치
Dashboard > Jenkins 관리 > Plugins > Avaliable plugins > ssh agent 검색
0.3 Jenkins key 발급
Dashboard > Jenkins 관리 > Credentials > System > Global credentials
1. Pipeline Script : 단순배포
def deployApp(String targetServerIp) {
def jarPath = 'build/libs/inclass-spring-security-0.0.1-SNAPSHOT.jar'
def deployPath = '/home/ubuntu'
def runAppCommand = "nohup java -jar $deployPath/inclass-spring-security-0.0.1-SNAPSHOT.jar > nohup.log 2>&1 &"
def checkLogCommand = "grep -q 'Started Application in' $deployPath/nohup.log"
sshagent(['A-jenkins-key']) {
echo "Stopping previous deployment..."
// 이전에 실행 중인 Java 프로세스 종료
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\"'"
// JAR 파일 전송
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}'"
sleep 30
}
}
pipeline {
agent any
environment {
GRADLE_HOME = tool 'GRADLE'
}
stages {
stage('Clone') {
steps {
git branch: 'master', url: 'https://github.com/nayeo2/KDT_prj_application.git'
}
}
stage('Test') {
steps {
script {
sh 'chmod +x ./gradlew'
sh './gradlew test'
}
}
}
stage('Build') {
steps {
sh "${GRADLE_HOME}/bin/gradle clean build"
sh './gradlew clean build -Pdb.url=jdbc:mysql://10.0.3.31:3306/spring_security_inclass?useSSL=false -Pdb.username=master -Pdb.password=0808 -Pdb.driver=com.mysql.cj.jdbc.Driver'
sh 'ls build/libs'
}
}
stage('Deploy') {
steps {
script {
// 배포 함수 호출
deployApp('10.0.2.99')
}
}
}
}
post {
success {
echo 'Pipeline completed successfully.'
}
failure {
echo 'Pipeline failed.'
}
}
}
과정 중 DB 연동 실패 오류가 있었음.
앞 게시물에서 언급했듯이 새로운 유저를 생성하고 데이터베이스 접근 권한을 줘야함.
참조 SQL 쿼리는 아래와 같음
# 사용자 생성
CREATE USER '생성할 유저명'@'#' IDENTIFIED BY '비밀번호';
# 권한 부여
GRANT ALL PRIVILEGES ON spring_security_inclass.* TO '유저명'@'%';
# 변경 사항 적용
FLUSH PRIVILEGES;