devops(?)

Github action 으로 EC2 에 spring boot 배포하기(3)

방금시작한사람 2020. 8. 7. 19:38

이제 CodeDeploy 에 들어가면 설정을 합니다..

 

AWS Codedeploy 에 들어가서 배포 -> 애플리케이션 -> 애플리케이션 생성 을 합니다

 

생성

컴퓨터 플랫폼만 EC2/온프레미스로 해주세요

 

생성 후에 배포 그룹 생성 클릭

 

 

그룹이름은 자유롭게 하시고, 역할은 아까 IAM 에서 Codedeploy 를 위해 만든 역할이 있을겁니다.

 

배포 유형 - 현재위치

환경 구성 - Amazon EC2 인스턴스 에서 사용하고싶은 EC2 를 골라주시면 됩니다.

AWS Systems Manager - 아까 EC2에 Codedeploy agent 를 설치했기 때문에 편하신거 고르시면 됩니다

배포설정 - CodedeployDeafault.AllAtOnce 

로드밸런싱활성화 - 저는 Application Load Balancer 를 사용하고 있기때문에 선택했습니다.

 

이제 애플리케이션과 배포 그룹을 만들었습니다!

 

배포를 해야되는데 배포 할 때 사용할 설정 파일이 필요합니다

 

appspec.yml 이라는 파일을 만들어야됩니다. 

이 설정 배포를 할때, EC2에 파일이 어디서 옮겨지는지, 그 다음에 뭘 할것인지에 대해 설정하는 파일입니다.

 

version: 0.0
os: linux
files:
  - source: /
    destination: /home/ubuntu/codedeploy/test/ # 배포 파일 도착 폴더
    overwrite: yes 
    # 이 설정을 해도 덮어써지지 않는 다는 말이 있는데 저는 일단 잘되서 사용중입니다.
    # 제대로 되지않는다면, 아래 hooks BeforeInstall 를 추가하여, 존재하는 파일을 삭제하는 방법이 있습니다
permissions:
  - object: /
    pattern: "**" # 모든 파일의 권한 설정
    owner: ubuntu
    group: ubuntu

hooks:
  AfterInstall: # 파일이 도착 후 실행
    - location: deploy-community.sh 
      timeout: 60 # 60 안에 실행, 60 뒤엔 배포 실패로 변경
      runas: root
  ValidateService: # deploy-community 의 실행 후, 빌드파일이 배포가 되었다면, 서버체크
    - location: server-check.sh
      timeout: 60

 

이건 codedeploy 의 흐름도 입니다.

실행 순서

 

이제 Github Action에서 실행만 하면 끝!

 

# This workflow will build a Java project with Gradle
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle

name: Java CI with Gradle

on:
  push:
    branches: [ master, dev, feature/cicd ]
  pull_request:
    branches: [ master, dev ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: 11
      - name: Grant execute permission for gradlew
        run: |
          chmod +x gradlew
          ./gradlew build
          
      - name: If failure then upload test reports
        if: failure()
        run: |
          TARBALL_BASENAME="r6-community-report"
          TARBALL="$TARBALL_BASENAME.tar"

          echo 'Collecting the test report'
          find . -path '*/build/reports/tests' -type d \
            -exec tar rf "$TARBALL" \
              --xform="s:./:$TARBALL_BASENAME/:" \
              --xform='s:/build/reports/tests::' \
              {} ';'

          echo 'Compressing the test reports .. '
          gzip "$TARBALL"

          echo 'Uploading the test reports .. '
          curl -F "file=@$TARBALL.gz" 'https://file.io/'
          echo
          echo 'Download the test reports from the URL above.'
          
      - name: Zip build file and deploy sh
        run: |
          mv ./build/libs/r6-community-*.jar ./
          zip buildFile.zip ./deploy-community.sh ./appspec.yml ./r6-community-*.jar ./server-check.sh
          
      - name: Upload build file to S3
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_S3_UPLOAD }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_S3_UPLOAD_KEY }}
        run: |
          aws s3 cp \
            --region ap-northeast-2 \
            buildFile.zip s3://${{ secrets.AWS_S3_BUCKET_NAME }}/community-build/
            
      - name: Configure aws credential
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_DEPLOY }}
          aws-secret-access-key: ${{ secrets.AWS_DEPLOY_KEY }}
          aws-region: ap-northeast-2
          
      - name: Deploy ec2
        run: |
          aws deploy create-deployment \
            --application-name codedeploy-from-s3 \
            --deployment-group-name codedeploy-from-s3 \
            --s3-location bucket=${{ secrets.AWS_S3_BUCKET_NAME }},key=community-build/buildFile.zip,bundleType=zip > deploymentId.txt

          DEPLOYMENT_ID=$(cat deploymentId.txt | jq -r '.deploymentId')

          echo "Wait 60 seconds for deployment and test"
          sleep 60

          IS_SUCCESS=$(aws deploy get-deployment --deployment-id $DEPLOYMENT_ID | jq -r '.deploymentInfo.status')

          echo $IS_SUCCESS;

          if [ "$IS_SUCCESS" = "Succeeded" ];
          then
            echo "SUCCESS DEPLOY!"
          else
            echo "FAIL DEPLOY!"
            exit 1
          fi

 

갑자기 길어졌는데 그 이유는 배포 후 배포성공 여부까지 체크하기 때문입니다....

 

요약하자면

 

1) spring boot 빌드 

1 - 1) 빌드 실패 시, build 결과 report 

2) 빌드 후, appspec.yml, 스크립트(배포 및 서버 체크), build 파일을 압축

3) S3 zip 파일 업로드

4) aws configure

5) codedeploy 배포 생성

5 - 1) deploy 후 배포 결과 확인

 

 

압축하는 이유는 codedeploy 가 압축파일만을 가져올 수 있기 때문입니다(S3 기준)

 

DEPLOYMENT_ID 는 create-deployment 을 실행하면 나오는 ID 입니다.

그 아이디로 배포 결과를 조회할 수 있습니다.

https://docs.aws.amazon.com/cli/latest/reference/deploy/get-deployment.html

 

get-deployment — AWS CLI 1.18.114 Command Reference

Note: You are viewing the documentation for an older major version of the AWS CLI (version 1). AWS CLI version 2, the latest major version of AWS CLI, is now stable and recommended for general use. To view this page for the AWS CLI version 2, click here. F

docs.aws.amazon.com

 

 


 

이렇게해서 github action 을 활용한 CI / CD 가 끝났습니다!

 

설정하고 script 짜는데 되게 노가다를 많이 했네요;;

 

이게 되는지 하고 github action 에 올려봐야되서..ㅠㅠ 

 

그래도 조금이나마 shell script 짜는 방법(?) 을 배운거 같아 좋은 경험이었습니다....