[Jenkins] 깃 클론해서 Pipeline 구축하기

Na young·2024년 7월 10일
0

Jenkins

목록 보기
3/4

Pipeline syntax

pipeline {
		tools {
		    gradle "GRADLE" // Jenkins에서 설정한 Gradle의 이름
		}

    agent any
    stages {
        stage('Clone') {
            steps {
                [여기에 syntax에서 생성된 스크립트 입력하기]
            }
        }

        stage('Build') {
            steps {
                sh 'pwd'
                sh 'ls'
                sh './gradlew clean build'
                sh 'ls ./build/libs'
            }
        }
    }
}

  • gradle 툴을 코드에 추가해뒀기 때문에 tool에서 해당 GRADLE 추가

전송구문 작성하기

stage('Deploy') {
     steps {
          script {
     // Maven 빌드로 생성된 jar 파일의 위치
          	def jarPath = 'build/libs/파일명.jar'
    // 원격 서버의 IP 주소 및 배포 경로
            def targetServerIp = 'xxx.xxx.xxx.xxx'
            def deployPath = '/root'
            def runAppCommand = "java -jar $deployPath/파일명.jar"
                    
    // 서버에 파일을 SCP로 전송
    // 원격 서버에서 애플리케이션 실행
            sshagent(['비공개키명']) { // 'server-ssh-credentials'는 Jenkins에서 설정한 credentials ID
              		sh "scp -o StrictHostKeyChecking=no $jarPath 계정명@$targetServerIp:$deployPath/"
              }
                    
                    
      // 원격 서버에서 애플리케이션 실행
             sshagent(['비공개키명']) { // 'server-ssh-credentials'는 Jenkins에서 설정한 credentials ID
                     sh "ssh -o StrictHostKeyChecking=no 계정명@$targetServerIp '$runAppCommand'"
           }
     }
}

  • 비공개 키


-> 젠킨스 서버에서 만든 비밀키 넣어주면 됨

내 코드 : 백그라운드에서 실행하도록 수정함.

pipeline {
    tools {
        gradle "GRADLE" // Jenkins에서 설정한 Gradle의 이름
    }

    agent any
    stages {
        stage('Clone') {
            steps {
                git branch: 'main', url: '깃 주소'
            }
        }

        stage('Build') {
            steps {
                sh './gradlew clean build'
                sh 'ls ./build/libs'
            }
        }
        
        stage('Deploy') {
            steps {
                script {
                    // Maven 빌드로 생성된 jar 파일의 위치
                    def jarPath = 'build/libs/파일명.jar'
                    // 원격 서버의 IP 주소 및 배포 경로
                    def targetServerIp = '비공인 IP'
                    def deployPath = '경로 (나는 /home/ubuntu)'
                    def runAppCommand = "nohup java -jar $deployPath/파일명.jar &"

                    sshagent(['젠킨스 비밀키']) { // 'jenkins-ssh'는 Jenkins에서 설정한 credentials ID
                        sh "scp -o StrictHostKeyChecking=no $jarPath ubuntu@$targetServerIp:$deployPath/"
                        sh "ssh -o StrictHostKeyChecking=no ubuntu@$targetServerIp '$runAppCommand'"
                    }
                }
            }
        }
    }
}



리팩토링 : Deploy 단계 내부에서 서버 ip만 파라미터로 넘겨서 함수를 호출하도록

  • 한 줄만 하도록
// 함수 정의
def deployToServer(String targetServerIp) {
    // Maven 빌드로 생성된 jar 파일의 위치
    def jarPath = 'build/libs/파일명.jar'
    // 원격 서버의 배포 경로
    def deployPath = '/home/ubuntu'
    def runAppCommand = "nohup java -jar $deployPath/파일명.jar > nohup.log 2>&1 &"

    // 서버에 파일을 SCP로 전송
    sshagent(['젠킨스 비밀키']) {
        sh "scp -o StrictHostKeyChecking=no $jarPath ubuntu@$targetServerIp:$deployPath/"
        sh "ssh -o StrictHostKeyChecking=no ubuntu@$targetServerIp '$runAppCommand'"
    }
}

pipeline {
    tools {
        gradle "GRADLE" // Jenkins에서 설정한 Gradle의 이름
    }

    agent any
    stages {
        stage('Clone') {
            steps {
                git branch: 'main', url: 'https://github.com/깃주소.git'
            }
        }

        stage('Build') {
            steps {
                sh './gradlew clean build'
                sh 'ls ./build/libs'
            }
        }
        
        stage('Deploy') {
            steps {
                script {
                    // 실제 배포 함수 호출
                    deployToServer('타겟서버 비공인 IP')
                }
            }
        }
    }
}

  • 타겟 인스턴스에서 확인하기
    ps - aux | grep java

실행 여부를 echo를 통해 알려주고, post 블럭으로 메시지 보내고, 배포 전에 이전 프로세스 종료하는 구문 추가

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"

    sshagent(['젠킨스 비밀키']) {
        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

        // 애플리케이션 실행 확인
        def result = sh script: "ssh -o StrictHostKeyChecking=no ubuntu@$targetServerIp \"${checkLogCommand}\"", returnStatus: true
        if (result == 0) {
            echo 'Deployment was successful.'
        } else {
            error "Deployment failed: Could not find 'Started CpuboundappApplication in' in log."
        }
    }
}

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('타겟서버 비공인 IP')
                }
            }
        }
    }

    post {
        success {
            echo 'Pipeline completed successfully.'
        }
        failure {
            echo 'Pipeline failed.'
        }
    }
}


errorcode
grep: CpuboundappApplication: No such file or directory
grep: in: No such file or directory

! 아래와 같이 (2) 구문에 (1) checkLogCommand 함수가 들어가는거임, 의도는 (1)의 저 문장을 로그에서 찾아라. 인데 그대로 넣으면 따옴표 때문에 문자로 인식이 안돼서 역슬래시\를 추가함.

profile
개발어린이

0개의 댓글

관련 채용 정보