Jenkins

Jenkins 서버에서 3개의 원격서버에 배포하기

공부 기록장 2024. 11. 30. 20:22

1. Jenkins 서버와 3개의 원격서버에서 기본 세팅하기

 - Jenkins : 자바 JDK 설치, 개인키와 공개키 생성

 - 원격서버 : 자바 JDK 설치, ~/.ssh/authorized_keys 에 공개키 삽입

 

 

 

 

2. Jenkins 서버에서 Credentials 추가(개인키 삽입하기, 깃허브에 application.properties를 gitignore 처리했으면 application.properties 파일추가하기)

 

 

 

 

3. Jenkins 서버에서 파이프라인 작성

아래 스크립트는 애플리케이션을 백그라운드로 실행하도록 함. 

pipeline {
    agent any

    tools {
        gradle "Gradle" // Ensure the Gradle tool is configured in Jenkins
    }

    stages {
        stage('Clone Repository') {
            steps {
                git branch: 'master', url: 'https://github.com/DongHun3946/potHole_detectProject_springBoot.git', credentialsId: 'github_token'
            }
        }
        stage('Build with Gradle') {
            steps {
                sh 'chmod +x ./gradlew'
                sh './gradlew clean build'
            }
        }
        stage('Copy Application Properties') {
            steps {
                withCredentials([file(credentialsId: 'application_properties', variable: 'APP_PROPERTIES_FILE')]) {
                    script {
                        sh "cp $APP_PROPERTIES_FILE /var/jenkins_home/workspace/test_pipe/src/main/resources/application.properties"
                        sh "chmod u+w /var/jenkins_home/workspace/test_pipe/src/main/resources/application.properties"
                    }
                }
                echo 'Application properties copied successfully!'
            }
        }
        stage('Deploy to Server 1') {
            steps {
                script {
                    deployToServer("43.203.241.183")
                }
            }
        }
        stage('Deploy to Server 2') {
            steps {
                script {
                    deployToServer("13.124.93.111")
                }
            }
        }
        stage('Deploy to Server 3') {
            steps {
                script {
                    deployToServer("52.79.83.110")
                }
            }
        }
    }

    post {
        success {
            echo 'Deployment completed successfully.'
        }
        failure {
            echo 'Deployment encountered an error.'
        }
    }
}

def deployToServer(serverIp) {
    def jarFile = "${WORKSPACE}/build/libs/pothole_capstone-0.0.1-SNAPSHOT.jar"
    def deployPath = '/home/ubuntu'
    def runAppCommand = "nohup java -jar $deployPath/pothole_capstone-0.0.1-SNAPSHOT.jar > $deployPath/app.log 2>&1 &"
    def checkLogCommand = "grep -q 'Started' $deployPath/app.log"

    // Stop existing application on the server
    sshagent(['deploy_ssh_key']) { // Replace 'deploy_ssh_key' with the correct Jenkins credential ID
        sh script: "ssh -o StrictHostKeyChecking=no -i /var/jenkins_home/.ssh/id_rsa ubuntu@$serverIp 'pgrep -f pothole_capstone-0.0.1-SNAPSHOT.jar && pkill -f pothole_capstone-0.0.1-SNAPSHOT.jar || echo \"No process found\"'", returnStatus: true
    }

    // Transfer the new JAR file and application.properties to the server
    sh "scp -o StrictHostKeyChecking=no -i /var/jenkins_home/.ssh/id_rsa ${WORKSPACE}/build/libs/pothole_capstone-0.0.1-SNAPSHOT.jar ubuntu@$serverIp:$deployPath/"
    

    // Start the application on the remote server
    sshagent(['deploy_ssh_key']) { // Replace 'deploy_ssh_key' with the correct Jenkins credential ID
        sh "ssh -o StrictHostKeyChecking=no -i /var/jenkins_home/.ssh/id_rsa ubuntu@$serverIp '$runAppCommand'"
        sleep 20 // Allow time for the application to start

        // Verify the application started successfully
        int result = sh script: "ssh -o StrictHostKeyChecking=no -i /var/jenkins_home/.ssh/id_rsa ubuntu@$serverIp '$checkLogCommand'", returnStatus: true
        if (result == 0) {
            echo "Deployment to $serverIp was successful."
        } else {
            error "Deployment to $serverIp failed."
        }
    }
}

 

 

 

 

 

 

4. 3개의 원격서버에서 실행되고 있는지 확인해보기

현재 ubuntu 사용자가 8080 포트를 사용하고 있음을 알 수 있다.

 

 

3개의 원격서버 모두 애플리케이션이 백그라운드로 실행됨을 알 수 있다.

 

 

실행모습