[Jenkins] Jenkins를 활용한 CI/CD 파이프라인 구축 (3)

Jenkins, EC2, AWS, Docker, CI/CD

Featured image

[Jenkins] Jenkins를 활용한 CI/CD 파이프라인 구축 (3)

1. Git Credentials 관리



2. AWS Credentials 관리

environment {
  AWS_ACCESS_KEY_ID = credentials('awsAccessKeyId')
  AWS_SECRET_ACCESS_KEY = credentials('awsSecretAccessKey')
  AWS_DEFAULT_REGION = 'ap-northeast-2'
  HOME = '.' // Avoid npm root owned
}


3. Jenkinsfile stage 작성하기

stage('Prepare') {
    agent any
    
    steps {
        echo 'Clonning Repository'

        git url: 'https://github.com/YeonghyeonKO/Practice_Jenkins.git',
            branch: 'main',
            credentialsId: 'Wafflow'
    }

    post {
        // If Maven was able to run the tests, even if some of the test
        // failed, record the test results and archive the jar file.
        success {
            echo 'Successfully pulled Repository'
        }

        always {
            echo "i tried..."
        }

        cleanup {
            echo "after all other post condition"
        }
    }
}


stage('Deploy Frontend') {
  steps {
    echo 'Deploying Frontend'
    // 프론트엔드 디렉토리의 정적파일들을 S3 에 올림, 이 전에 반드시 EC2 instance profile 을 등록해야함.
    dir ('./website'){
        sh '''
        aws s3 sync ./ s3://wafflow-bucket
        '''
    }
  }

  post {
    // If Maven was able to run the tests, even if some of the test
    // failed, record the test results and archive the jar file.
    success {
      echo 'Successfully Cloned Repository'

      mail  to: 'dk02315@gmail.com',               
            subject: "Deploy Frontend Success",
            body: "Successfully deployed frontend!"

    }

    failure {
      echo 'I failed :('

        mail  to: 'dk02315@gmail.com',
              subject: "Failed Pipelinee",
              body: "Something is wrong with deploy frontend"
    }
  }
}


stage('Bulid Backend') {
  agent any
  steps {
    echo 'Build Backend'

    dir ('./server'){
        sh """
        docker build . -t server --build-arg env=${PROD}
        """
    }
  }

  post {
    failure {
      error 'This pipeline stops here...'
    }
  }
}


stage('Deploy Backend') {
  agent any

  steps {
    echo 'Build Backend'

    dir ('./server'){
        sh '''
        docker rm -f $(docker ps -aq)
        docker run -p 80:80 -d server
        '''
    }
  }

  post {
    success {
      mail  to: 'frontalnh@gmail.com',
            subject: "Deploy Success",
            body: "Successfully deployed!"
          
    }
  }
}


이제 네 번째 포스트에서 우리가 만든 Jenkinsfile이 실제로 어떻게 돌아가는지에 대해 살펴볼 것이다.



참고자료 : T-Academy Jenkins를 활용한 CI/CD