카테고리 없음

[Jenkins] (pull -> 빌드 -> 배포) 파이프라인 ex

개발에목마른쭌 2023. 6. 1. 11:02
pipeline {
    agent any
    
    environment {
        timestamp = "${System.currentTimeMillis() / 1000L}"
    }
    
    stages {
        stage('Prepare') {
            steps {
                script {
                    def oldImageId = sh(script: "docker images gram:latest -q", returnStdout: true).trim()
                    env.oldImageId = oldImageId
                }
            
                git branch: 'main',
                    url: 'https://github.com/jooooonj/GramGram_project'
            }
            
            post {
                success { 
                    sh 'echo "Successfully Cloned Repository"'
                }
                failure {
                    sh 'echo "Fail Cloned Repository"'
                }
            }  
        }
    
        stage('Build Gradle') {
            
            steps {
                
                dir('.') {
                    sh '''
                    cat <<EOF > src/main/resources/application-secret.yml
spring:
  datasource:
    url: 
    username: 
    password:
  security:
    oauth2:
      client:
        registration:
          naver:
            clientId: 
            client-secret: 
          kakao:
            clientId: 
          google:
            client-id: 
            client-secret: 
          facebook:
            clientId: 
            client-secret: 
          instagram:
            clientId: 
            client-secret: 
EOF
                    '''
                }
            
                dir('.') {
                    sh """
                    chmod +x gradlew
                    """
                }
                
                dir('.') {
                    sh """
                    ./gradlew clean build
                    """
                }
            }
            
            post {
                success { 
                    sh 'echo "Successfully Build Gradle Test"'
                }
                 failure {
                    sh 'echo "Fail Build Gradle Test"'
                }
            }    
        }
        
        stage('Build Docker Image') {
            steps {
                script {
                    sh "docker build -t gram:${timestamp} ."
                }
            }
        }

        stage('Run Docker Container') {
            steps {
                script {
                    // Check if the container is already running
                    def isRunning = sh(script: "docker ps -q -f name=gram_1", returnStdout: true).trim()

                    if (isRunning) {
                        sh "docker rm -f gram_1"
                    }
                    
                    // Run the new container
                    try {
                        sh """
                        docker run \
                          --name=gram_1 \
                          -p 8080:8080 \
                          -v /docker_projects/gram/volumes/gen:/gen \
                          --restart unless-stopped \
                          -e TZ=Asia/Seoul \
                          -d \
                          gram:${timestamp}
                        """
                    } catch (Exception e) {
                        // If the container failed to run, remove it and the image
                        isRunning = sh(script: "docker ps -q -f name=gram_1", returnStdout: true).trim()
                        
                        if (isRunning) {
                            sh "docker rm -f gram_1"
                        }
                        
                        def imageExists = sh(script: "docker images -q gram:${timestamp}", returnStdout: true).trim()
                        
                        if (imageExists) {
                            sh "docker rmi gram:${timestamp}"
                        }
                        
                        error("Failed to run the Docker container.")
                    }

                    // If there's an existing 'latest' image, remove it
                    def latestExists = sh(script: "docker images -q gram:latest", returnStdout: true).trim()
                    
                    if (latestExists) {
                        sh "docker rmi gram:latest"
                        
                        if(!oldImageId.isEmpty()) {
                        	sh "docker rmi ${oldImageId}"
                        }
                    }

                    // Tag the new image as 'latest'
                    sh "docker tag gram:${env.timestamp} gram:latest"
                }
            }
        }
    }
}