티스토리 뷰

Pipline 구성

Pipline을 구성하기 위해 내부를 채운다.

  • agent : 스테이지 별로 수행할 agent를 선언한다.
  • triggers : 얼마를 주기로 수행할 것인지 설정.
  • enviornment : 전 포스트글에서 정리한 내용들이 들어가는 것으로 환경변수 등을 세팅
  • stages : 일련의 목차들을 담고 있는 곳
    • stage : 목차

 

stage : prepare

// 레포지토리를 다운로드 받음
        stage('Prepare') {
            agent any
            
            steps {
                echo 'Clonning Repository'

                git url: 'https://github.com/choiwoonsik/jenkinsTest',
                    branch: 'master',
                    credentialsId: 'gitForJenkins'
            }

            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 내에 step이 존재한다. steps에 수행할 step들이 존재한다.

  • git url, branch, (jenkins에 등록한) git Credentials ID를 작성해서 pull 받는다.
  • 요청이 수행되면 아래 post를 통해 추가 수행을 진행한다.

success : 성공 시 처리

always : 항상 처리

cleanup : 추가작업 수행 후

 

stage : Only for production

        stage('Only for production') {
          when {
            branch 'production'
            environment name: 'APP_ENV', value: 'prod'
            anyOf {
              environment name: 'DEPLOY_TO', vlaue: 'production'
              environment name: 'DEPLOY_TO', value: 'staging'
            }
          }
        }

when

  • 위 경우에는 branch가 production, APP_ENV가 prod일 경우에만 수행하도록 하는 것.
  • 특정 조건에만 수행하도록 할 수 있다.

 

stage : Deploy Frontend

        // aws s3 에 파일을 올림
        stage('Deploy Frontend') {
          steps {
            echo 'Deploying Frontend'
            // 프론트엔드 디렉토리의 정적파일들을 S3 에 올림, 이 전에 반드시 EC2 instance profile 을 등록해야함.
            dir ('./website'){
                // 배포를 위한 핵심 로직이 들어가는 부분이다.
                sh '''
                aws s3 sync ./ s3://wsjenkinss3
                '''
            }
          }

          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: 'frontalnh@gmail.com',
                        subject: "Deploy Frontend Success",
                        body: "Successfully deployed frontend!"

              }

              failure {
                  echo 'I failed :('

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

AWS의 S3에 원하는 파일을 올릴려는 stage

  • environment에서 AWS 관련 환경변수를 설정을 해줌으로서 가능하다.

 

dir ('./website')

  • jenkins가 해당 디렉토리를 루트 디렉토리로 삼기 위해 이동하는 것. (실행할 파일이 해당 디렉토리에 있음)

 

배포를 위한 코드

  • sh ```aws s3 sync ./ s3://wsjenkinss3```
  • 현재 디렉토리를 s3://{나의 s3 주소}에 복사한다.

 

step이 끝난 후 post를 진행

  • success / failure 둘다 mail 이 존재하는데 두 경우 모두 메일로 결과를 알려주기 위한 용도이다.
  • jenkins 관리 -> 시스템 설정 -> 맨 아래에 E-mail로 알려줌으로 가서 아래와 같이 설정하면 결과를 이메일로 보낼 수 있다.

Gmial 아이디와 비밀번호를 jenkins에 등록

 

stage : Lint Backend

        stage('Lint Backend') {
            // Docker plugin and Docker Pipeline 두개를 깔아야 사용가능!
            agent {
              docker {
                image 'node:latest'
              }
            }
            
            steps {
              dir ('./server'){
                  sh '''
                  npm install&&
                  npm run lint
                  '''
              }
            }
        }

Q. agent가 docker { image 'node:latest' } 로 되어있다. 왜일까?

A. 현재 서버가 node인데 jenkins에 노드가 없다.

그래서 jenkins에게 docker image에서 node:latest를 받고 해당 컨테이너에서 steps에 있는 명령어를 수행하라는 의미이다.

 

즉, agent는 step을 수행할 slave node이고 해당 단계에서는 최신 node 도커 이미지로 수행하라는 것이다.

 

stage : Build Backend

        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...'
            }
          }
        }

도커 이미지를 생성해주고 배포환경에 대한 환경변수도 설정해준다.

 

post에서 실패한 경우 error를 뱉도록 되어있다. 배포를 실패한 경우 파이프라인을 그만두고 종료하기 위한 것.

 

stage : Deploy Backend

        stage('Deploy Backend') {
          agent any

          steps {
            echo 'Build Backend'

            dir ('./server'){
              // docker rm -f $(docker ps -aq) 컨테이너가 돌고 있을 경우 제거
                sh '''
                docker run -p 80:80 -d server
                '''
            }
          }

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

빌드한 도커 이미지를 배포해준다. 배포에 성공한 경우 이메일 전송까지 수행.

 


Jenkins 실제 적용

 

Jenkins 플러그인 추가

  • 필요한 플러그인들을 [jenkins 관리 -> 플러그인 관리]에서 추가해준다.
  • docker, docker pipline 외 필요한 플러그인 들

 

jenkins 아이템 생성

  • 대시보드 -> 새로운 Item -> 원하는 이름으로 pipeline을 생성한다.

파이프라인에 작성한 파이프라인 코드를 복사해 넣는다.

 

Jenkins파일 자동화 연동

Git에서 Jenkinsfile를 자동으로 찾아서 해당 코드를 가져오도록 할 수도 있다.

 

슬랙 알림 설정하기

  • 플러그인에 Slack Notification 추가
  • [jenkins 관리 -> 시스템 구성]에서 슬랙 알림을 설정해준다.
    • 팀 하위 도메인: slack 조직 명
    • 통합 토큰 자격 증명 ID: 발급받은 토큰을 Credentials에 등록해서 사용한다.
  • [Jenkinsfile]을 수정한다. pipleline을 수정함

 

원하는 stage에서 아래와 같은 코드를 추가한다.

slackSend (channel: '#jenkinstest', color: '#00FF00', message: "Successfully Deploy fronted")

위와같이 추가하면 다음과 같이 적용되는것을 확인할 수 있다.

 

마무리

Jenkins를 이용해서 pipeline을 작성해서 AWS S3에 로컬 파일을 복사하고, 원하는 도커 이미지를 받아서 해당 환경에서 빌드를 시키고, 테스트를 진행한 후에 docker 이미지를 만들고 해당 이미지를 배포까지 진행해 보았다.

 

중간에 빌드과정을 알려주는 용도로 Email과 Slack사용법을 알아보았고 성공적으로 배포 및 슬랙 알림까지 확인해 봤다. 간단하게 진행해 봤지만 매우 유용할것으로 보이고 이를 실제 프로젝트에 적용시키기 위해 좀 더 알아봐야겠다. 끝!

 

반응형
Comments
반응형
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday