아래와 같은 구조로 무중단배포를 구현하려고 한다.
이번 글에선 GitLab에서 빌드를 진행하여 생성된 Jar 파일을 AWS S3에 올려본다.
S3에 올려놓고 이후 AWS CodeDeploy를 통해 배포 요청이 발생하면 S3에서 Jar 파일을 가져다가 프로그램을 실행한다.
AWS S3 버킷 생성하기
먼저 Jar 파일을 저장할 S3의 버킷을 생성한다.
AWS IAM S3 사용자 생성하기
GitLab이 S3 버킷에 파일을 업로드 할 수 있도록 AmazonS3FullAccess 정책을 가진 사용자를 생성한다. (물론 특정 버킷에 대한 권한만 가진 정책을 만드는 게 좋다.)
사용자 생성 후 Access key ID와 Secret access key를 .csv 파일로 다운받아 관리한다. 페이지를 벗어나면 다시 확인이 불가능하고 새로 발급받아야 한다.
GitLab AWS 키 등록하기
[Settings] - [CI/CD] - [Variables] 메뉴에서 이전 단계에서 발급받은 AWS 키를 다음 이름의 변수로 등록한다.
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
여기서 등록한 키로 aws 사용자 로그인을 해줘서 .gitlab-ci.yml
파일에서 aws
커맨드를 사용할 수 있다.
protected 플래그를 체크하면, protected된 브랜치와 태그에서 실행되는 파이프라인에서만 해당 변수를 사용할 수 있다.
(protected된 브랜치, 태그는 delete, force push 등이 막힌다. master 브랜치는 기본으로 protected 되어 있다. [Settings] - [Branches] - [Protected Branches, Protected Tags]에서 protected 상태를 바꿀 수 있다.)
.gitlab-ci.yml 파일 작성하기
GitLab의 CI/CD 파이프라인은 .gitlab-ci.yml
파일에 정의된대로 실행된다.
이 파일에서 파이프라인에서 실행될 job들을 설정해주는 것이다.
프로젝트의 최상단에 .gitlab-ci.yml
파일을 생성하고 레퍼런스를 참고하여 내용을 작성해준다.
GitLab CI/CD Pipeline Configuration Reference | GitLab
docs.gitlab.com
나는 아래와 같이 작성해봤다.
# '숫자.숫자.숫자' 형식의 태그에 대해서만 파이프라인을 실행한다.
workflow:
rules:
- if: $CI_COMMIT_TAG =~ /^\d{1,}\.\d{1,}\.\d{1,}$/
when: always
# build, deploy 두 단계가 있다.
stages:
- build
- deploy
# 사용할 변수를 선언해준다.
variables:
S3_BUCKET_NAME: "my-demo-build"
JAR_PATH: ./demo-$CI_COMMIT_TAG.jar
# build 단계의 job 1
# jdk 도커 이미지로 도커 컨테이너를 생성하고
# maven으로 프로젝트를 빌드한다.
# artifacts를 설정해주어야 다음 단계에서 빌드된 파일에 접근 가능하다.
build:
stage: build
image: openjdk:8-jdk-alpine
script:
- chmod +x mvnw
- ./mvnw clean package
- cp ./target/demo-*.jar $JAR_PATH
artifacts:
paths:
- $JAR_PATH
expire_in: 1 day
# deploy 단계의 job 1
# python 도커 이미지로 도커 컨테이너를 생성하고
# awscli를 설치한 후 s3에 빌드된 파일을 업로드 한다.
push-to-s3:
stage: deploy
image: python:latest
script:
- pip install awscli
- aws s3 cp $JAR_PATH s3://$S3_BUCKET_NAME/
위 파일에서는 build, push-to-s3 두 개의 job을 명시했다.
Job Parameter
job은 결국 어떤 동작을 할 건지 정하는 파라미터들의 목록으로, 아래와 같은 파라미터들이 있다.
Keyword | Description |
script | Shell script which is executed by Runner. |
image | Use docker images. Also available: image:name and image:entrypoint. |
services | Use docker services images. Also available: services:name, services:alias, services:entrypoint, and services:command. |
before_script | Override a set of commands that are executed before job. |
after_script | Override a set of commands that are executed after job. |
stages | Define stages in a pipeline. |
stage | Defines a job stage (default: test). |
only | Limit when jobs are created. Also available: only:refs, only:kubernetes, only:variables, and only:changes. |
except | Limit when jobs are not created. Also available: except:refs, except:kubernetes, except:variables, and except:changes. |
rules | List of conditions to evaluate and determine selected attributes of a job, and whether or not it is created. May not be used alongside only/except. |
tags | List of tags which are used to select Runner. |
allow_failure | Allow job to fail. Failed job doesn’t contribute to commit status. |
when | When to run job. Also available: when:manual and when:delayed. |
environment | Name of an environment to which the job deploys. Also available: environment:name, environment:url, environment:on_stop, environment:auto_stop_in and environment:action. |
cache | List of files that should be cached between subsequent runs. Also available: cache:paths, cache:key, cache:untracked, and cache:policy. |
artifacts | List of files and directories to attach to a job on success. Also available: artifacts:paths, artifacts:expose_as, artifacts:name, artifacts:untracked, artifacts:when, artifacts:expire_in, artifacts:reports, artifacts:reports:junit, and artifacts:reports:cobertura. In GitLab Enterprise Edition, these are available: artifacts:reports:codequality, artifacts:reports:sast, artifacts:reports:dependency_scanning, artifacts:reports:container_scanning, artifacts:reports:dast, artifacts:reports:license_management, artifacts:reports:performance and artifacts:reports:metrics. |
dependencies | Restrict which artifacts are passed to a specific job by providing a list of jobs to fetch artifacts from. |
coverage | Code coverage settings for a given job. |
retry | When and how many times a job can be auto-retried in case of a failure. |
timeout | Define a custom job-level timeout that takes precedence over the project-wide setting. |
parallel | How many instances of a job should be run in parallel. |
trigger | Defines a downstream pipeline trigger. |
include | Allows this job to include external YAML files. Also available: include:local, include:file, include:template, and include:remote. |
extends | Configuration entries that this job is going to inherit from. |
pages | Upload the result of a job to use with GitLab Pages. |
variables | Define job variables on a job level. |
interruptible | Defines if a job can be canceled when made redundant by a newer run. |
resource_group | Limit job concurrency. |
참고: docs.gitlab.com/12.10/ee/ci/yaml/#parameter-details
job마다 중복되는 설정들이 있어 전역적으로 한 번만 설정하고 싶다면 default: 키워드를 사용하면 된다.
참고: docs.gitlab.com/12.10/ee/ci/yaml/#setting-default-parameters
Predefined environment variables
$CI_COMMIT_TAG 처럼 이미 정의된 변수들을 활용할 수 있다.
참고:docs.gitlab.com/ee/ci/variables/predefined_variables.html
Variables Expressions
최상단의 workflow: 키워드는 파이프라인을 생성할지 말지 결정한다.
어떤 특정 문자열과 일치할 때만 생성하게 할 수도, 정규표현식과 일치할 때만 생성하게 할 수도 있다.
정규표현식은 양 끝을 /
로 열고 닫아야 하며, 정규표현식의 일치 부등호는 =~
, 불일치 부등호는 !~
이다.
$VARIABLE =~ /^content.\*/
$VARIABLE\_1 !~ /^content.\*/
참고: docs.gitlab.com/ee/ci/variables/README.html#environment-variables-expressions
AWS S3 Command
참고: docs.aws.amazon.com/ko_kr/cli/latest/reference/s3/cp.html
GitLab pipeline
이제 커밋을 하고 푸시를 하면 [CI/CD] - [pipelines] 메뉴에서 파이프라인이 생성되고 실행되는 것을 볼 수 있다.
클릭해보면 job별 진행 상태, 로그, 소요 시간등을 확인할 수 있고 원하는 job만 재실행할 수도 있다.
GitLab 파이프라인이 성공하고
S3를 확인해보면 제대로 Jar가 저장되어 있다!
'DevOps' 카테고리의 다른 글
AWS 자동 배포하기 (2) - CodeDeploy : 무중단배포 (0) | 2021.03.18 |
---|---|
Shell 셸, 셸 스크립트 (0) | 2021.01.30 |
AWS 자동 배포하기 (1) - EC2, Auto Scaling, Load Balancing (0) | 2021.01.24 |
AWS RDS(Relational Database Service) 기본 (0) | 2021.01.03 |
도커란 (0) | 2020.11.24 |