개발
AWS EC2에서 GitLab CI/CD 파이프라인 구축하기
velca
벨바카
2024년 10월 14일 10시 54분

AWS EC2

AWS EC2(Elastic Compute Cloud)는 아마존 웹 서비스에서 제공하는 가상 서버 호스팅 서비스이다. 사용자는 EC2를 통해 필요에 따라 서버를 생성하고 관리할 수 있으며, 다양한 운영 체제와 소프트웨어를 설치할 수 있다.

EC2는 유연한 스케일링, 다양한 인스턴스 유형, 그리고 높은 가용성을 제공하여 웹 애플리케이션을 호스팅하는 데 적합하다.

고가용성 서버는 장애가 발생하더라도 서비스 중단 시간을 최소화하고, 사용자에게 안정적인 서비스를 제공하는 것을 목표로 한다.

GitLab CI/CD 파이프라인

GitLab CI/CD는 GitLab에서 제공하는 지속적 통합(Continuous Integration) 및 지속적 배포(Continuous Deployment) 도구다. CI/CD 파이프라인은 코드 변경 사항을 테스트하고 배포하는 프로세스를 자동화하여 개발자들이 더 빠르고 안정적으로 소프트웨어를 배포할 수 있도록 돕는다. GitLab CI/CD는 GitLab 저장소와 통합되어, 코드 Push 시 자동으로 빌드, 테스트, 배포 작업을 수행한다.

GitHub에는 GitHub Actions라고 비슷한 역할을 수행하는 서비스가 있다.

GitLab 프로젝트 설정

GitLab CI/CD를 사용하려면 GitLab에서 프로젝트 설정을 변경 해줘야 한다.

  1. 프로젝트에서 "Settings" > "CI/CD" > "Runners" > "New project runner" 클릭
  2. 필요한 내용들을 입력하고 "Create Runner" 클릭

    GitLab Runner 에서 태그는 특정 Runner가 특정 작업(Job)을 실행할 수 있도록 지정하는 메타데이터로, 작업 할당, 환경 분리, 리소스 관리 등을 위해 사용된다.
    간단한 역할로는 이후 생성할 .gitlab-ci.yml 에서 동일한 태그를 가진 stage의 작업만 실행하기 위함이다.
  3. Runner 실행 플랫폼에 따라 register 방법을 안내하는 화면에서 token 정보 확인

    등록 토큰은 현재 화면에서 밖에 보이지 않기 때문에 분실하면 안된다.

EC2에 GitLab Runner 설치

다음은 EC2 인스턴스에 GitLab Runner를 설치해야 한다. EC2 인스턴스 생성 방법부터 알아보자.

1. EC2 인스턴스 생성

  1. AWS Management Console에 로그인
  2. EC2 대시보드로 이동 후 "Launch Instance" 클릭
  3. 원하는 AMI(Amazon Machine Image) 선택 및 인스턴스 유형 선택
    • 현재 글은 Ubuntu 기준으로 작성
  4. Security Group 에서 SSH(22), HTTP(80), HTTPS(443) 포트 열기
    • 22번 포트는 보안을 위해 특정 IP에서만 접속 가능하도록 설정
  5. 인스턴스를 시작 후 SSH 접속
    • 접속할 인스턴스 선택 후 "Connect" 클릭
    • 이후 SSH Client 탭의 안내 절차에 따라 SSH 접속

2. GitLab Runner 설치

SSH로 EC2 인스턴스에 접속 후 아래 명령어로 GitLab Runner를 설치.

sudo apt-get update
sudo apt-get install -y gitlab-runner

GitLab 프로젝트에서 Runner 생성 후 얻은 등록 토큰을 이용해 프로젝트 등록.

sudo gitlab-runner register

이후 나오는 프롬프트에 답변 해주면 된다.

GitLab URL은 GitLab 저장소를 사용하고 있으면 https://gitlab.com/을 입력하면 되고, token은 등록 토큰을, 실행기는 shell 을 입력해준다.

보다 자세한 설정 방법은 https://docs.gitlab.com/runner/register/ 를 확인하자.

GitLab 파이프라인 설정

1. .gitlab-ci.yml 파일 작성

프로젝트 루트 디렉토리에 .gitlab-ci.yml 파일을 생성하고, 파이프라인에서 실행 할 각 단계를 정의한다. .gitlab-ci.yml 파일은 CI/CD 프로세스에서 실행할 작업들을 설정한다.

예시 파일을 보려면 GitLab 프로젝트 페이지에서 "+ Set up CI/CD" 버튼을 누른 뒤 "Configure pipeline" 버튼을 누른다.

# This file is a template, and might need editing before it works on your project.
# This is a sample GitLab CI/CD configuration file that should run without any modifications.
# It demonstrates a basic 3 stage CI/CD pipeline. Instead of real tests or scripts,
# it uses echo commands to simulate the pipeline execution.
#
# A pipeline is composed of independent jobs that run scripts, grouped into stages.
# Stages run in sequential order, but jobs within stages run in parallel.
#
# For more information, see: https://docs.gitlab.com/ee/ci/yaml/index.html#stages
#
# You can copy and paste this template into a new `.gitlab-ci.yml` file.
# You should not add this template to an existing `.gitlab-ci.yml` file by using the `include:` keyword.
#
# To contribute improvements to CI/CD templates, please follow the Development guide at:
# https://docs.gitlab.com/ee/development/cicd/templates.html
# This specific template is located at:
# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Getting-Started.gitlab-ci.yml

stages:          # List of stages for jobs, and their order of execution
  - build
  - test
  - deploy

build-job:       # This job runs in the build stage, which runs first.
  stage: build
  script:
    - echo "Compiling the code..."
    - echo "Compile complete."

unit-test-job:   # This job runs in the test stage.
  stage: test    # It only starts when the job in the build stage completes successfully.
  script:
    - echo "Running unit tests... This will take about 60 seconds."
    - sleep 60
    - echo "Code coverage is 90%"

lint-test-job:   # This job also runs in the test stage.
  stage: test    # It can run at the same time as unit-test-job (in parallel).
  script:
    - echo "Linting code... This will take about 10 seconds."
    - sleep 10
    - echo "No lint issues found."

deploy-job:      # This job runs in the deploy stage.
  stage: deploy  # It only runs when *both* jobs in the test stage complete successfully.
  environment: production
  script:
    - echo "Deploying application..."
    - echo "Application successfully deployed."

위 내용은 예시 파일인데 보다 자세한 내용을 여기서 다루긴 어렵기 때문에 공식 문서 에서 확인하자.

2. GitLab에 코드 Push

모든 설정이 완료 되었다면 작성한 코드를 GitLab 프로젝트에 Push 하면 GitLab 파이프라인이 자동으로 실행된다.

댓글
로그인 후 댓글을 작성하세요