[6주차] Jenkins 환경에서의 CloudFront, S3 배포 자동화 (Next SSR)

[월간-CS][24년 4월] React, Next 배포와 배포 자동화 A부터 Z
이민석's avatar
May 13, 2024
[6주차] Jenkins 환경에서의 CloudFront, S3 배포 자동화 (Next SSR)

이 문서는 [월간-CS][24년 4월] React, Next 배포와 배포 자동화 A부터 Z를 위해서 작성된 문서입니다. 이 문서에는 그 어떤 저작권이 없으며, 편하게 참고 및 사용하셔도 됩니다.

개요

Jenkins 실행을 위한 EC2 준비하기

  1. AWS Console에서 EC2 검색하고 클릭하기

  2. 좌측 슬라이드에서 [네트워크 및 보안] - [보안 그룹] 클릭하기

  3. 우상단 주황색의 [보안 그룹 생성] 버튼 클릭하기

  4. 주요 설정값들을 아래와 같이 설정하고 생성하기

    • 기본 세부 정보

      • 보안 그룹 이름 : monthly-cs-sg-jenkins-server

      • 설명 : SSH

      • VPC: Default VPC 선택 유지

    • 인바운드 규칙

      • 유형 : SSH

      • 프로토콜 : TCP

      • 포트범위 : 22

      • 소스 : Anywhere IPv4

        주의

        실습 간에 사용할 EC2 Instance Connect를 위해서 Anywhere IPv4를 선택했습니다. 실제로는 내 IP를 선택하셔야 합니다. 실습 종료 이후에는 내 IP로 변경하거나 바로 EC2를 지우는 것을 권장합니다.

  5. 좌측 슬라이드에서 [인스턴스] - [인스턴스] 클릭하기

  6. 우상단 주황색의 [인스턴스 시작] 버튼 클릭하기

  7. 주요 설정값들을 아래와 같이 선택하고 시작하기

    1. 이름 및 태그 - 이름 : monthly-cs-ec2-jenkins-server

    2. 애플리케이션 및 OS 이미지 : Ubuntu Server 24.04 LTS (HVM), SSD Volume Type

    3. 인스턴스 유형 : t3.medium

    4. 키 페어(로그인) : monthly-cs-ec2-keypair

    5. 네트워크 설정 - 네트워크 : 기본으로 선택되어 있는 default vpc 유지

    6. 스토리지 구성 : 1x 3GiB gp3 선택

  8. 좌측 슬라이드에서 [인스턴스] - [인스턴스] 클릭하기

  9. 생성된 EC2:monthly-cs-ec2-jenkins-server에 우클릭하고 [연결] 클릭하기

  10. [EC2] - [인스턴스] - [i-**********] - [EC2 인스턴스 연결] - [EC2 직렬 콘솔] 선택 이후기본값 건드리지 말고 [연결] 클릭하기

    1. 연결 유형 : EC2 Instance Connect을 사용하여 연결

    2. 사용자 이름 : ubuntu

Jenkins 설치 및 환경 설정하기

Jenkins (Docs) | Installing Jenkins를 참고하여 진행합니다.

  1. 우측 [Chapter Sub Section] - [Linux] 선택하기

  2. 중앙의 [Debian/Ubuntu] 선택하기

  3. 아래 커멘드를 통해서 Jenkins for Debian/Ubuntu LTS 다운로드 받기

    sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \
      https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key
    
    echo "deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc]" \
      https://pkg.jenkins.io/debian-stable binary/ | sudo tee \
      /etc/apt/sources.list.d/jenkins.list > /dev/null
    sudo apt-get update
    sudo apt-get install jenkins
  4. 아래 명령어로 Jenkins 실행 상태 확인하기
    아마도 에러가 뜰 것입니다.

    sudo systemctl status jenkins
  5. Installing Java for Jenkikns 설치하기

    sudo apt update
    sudo apt install fontconfig openjdk-17-jre
    java -version
    openjdk version "17.0.8" 2023-07-18
    OpenJDK Runtime Environment (build 17.0.8+7-Debian-1deb12u1)
    OpenJDK 64-Bit Server VM (build 17.0.8+7-Debian-1deb12u1, mixed mode, sharing)
  6. 아래 명령어로 jenkins 실행하기

    sudo systemctl start jenkins
    sudo systemctl enable jenkins
  7. 주요 구문 확인하기

    구문

    설명

    sudo systemctl start jenkins

    Jenkins 시작

    sudo systemctl stop jenkins

    Jenkins 중단

    sudo systemctl restart jenkins

    Jenkins 재시작

    sudo systemctl status jenkins

    Jenkins 상태 확인

    sudo systemctl enable jenkins

    Jenkins 자동 시작 활성화

    sudo systemctl disable jenkins

    Jenkins 자동 시작 비활성화

  8. Jenkins 설정 파일 확인하기

    cat /etc/default/jenkins
  9. Jenkins 외부 포트 확인하기

    cat /etc/default/jenkins | grep -e PORT
  10. Curl 이용해서 서버 확인하기

    만약 Jenkines 외부 포트가 8080이 아니면 해당 포트로 curl을 보내세요.

    curl 127.0.0.1:8080
  11. 브라우저에서 <EC2 Public IPv4>:<Jenkins_Port>의 형태로 접속 시도하기

    왜 접속이 안될까? 생각해보기

Jenkins 접속을 위한 EC2 SG 수정하기

  1. AWS Console에서 EC2 검색하고 클릭하기

  2. 좌측 슬라이드에서 [네트워크 및 보안] - [보안 그룹] 클릭하기

  3. 보안 그룹 리스트에서 monthly-cs-sg-jenkins-server 클릭하기

  4. 인바운드 규칙에 아래 규칙 추가하기

    1. 유형 : 사용자 지정 TCP

    2. 프로토콜 : TCP

    3. 포트범위 : 8080

    4. 소스 : 내 IP

Jenkins 접속하고 환경 설정 설정 이어하기

  1. 다시 브라우저에서 <EC2 Public IPv4>:<Jenkins_Port>의 형태로 접속 시도하기

  2. EC2 Instance Connect에서 아래 구문을 입력해서 비밀번호 확인하기

    sudo cat /var/lib/jenkins/secrets/initialAdminPassword
  3. 비밀번호 입력하고 로그인하기

  4. 추천 플러그인 설치하기 클릭하기

  5. Admin User 생성하기

    1. 계정명 : unchaptered

    2. 암호 : 하이마트12@

    3. 이름 : 이민석

    4. 이메일 주소 : workstation19961002@gmail.com

  6. 그 외의 설정값 전부 건드리지말고 [Start using Jenkins] 버튼 나올때까지 다음으로 누르기. 해당 버튼이 나오면 클릭하세요.

Jenkins 파이프라인 구성하기

  1. 좌측 슬라이드에 [+ 새로운 Item] 클릭하기

  2. [Dashbaord] - {All] - [Enter an item name] 에서 이름, 유형 선택하고 파란색 [OK] 버튼 클릭하기

    이름은 GitHub Repository 이름에 맞춰서 2024-04-cicd-week-6-template로 하였습니다.

    • 이름 : 2024-04-cicd-week-6-template

    • 유형 : Pipeline

  3. [Dashboard] - [2024-04-cicd-week-6-template] - [Configuration] - [General]에서 [이 빌드는 매개변수가 있습니다.] 활성화

    1. 타입 : String Parameter

    2. 매개변수 명 : BRANCH

    3. Default Value : main

    4. 설명 : Main 브런치 용 Jenkins Pipeline

    5. Trim the string : 활성화

  4. [Dashboard] - [2024-04-cicd-week-6-template] - [Pipeline]에서 Pipeilne Script 입력하기

    pipeline {
        agent any
    
        stages {
            stage('prepare') {
                steps {
                    echo 'prepare'
                }
            }
            stage('build') {
                steps {
                    echo 'build'
                }
            }
            stage('deploy') {
                steps {
                    echo 'deploy'   
                }
            }
        }
    }
    
  5. [Dashboard] - [2024-04-cicd-week-6-template] - [Pipeline] 설정값 저장하기

  6. [Dashboard] - [2024-04-cicd-week-6-template]의 좌측 슬라이드에서 [파라미터와 함께 빌드] 클릭하기

    기본값 유지하고 바로 빌드 눌러보면 실행 결과를 볼 수 있습니다.

  7. 좌측 상단의 [Dashboard] 클릭하기

  8. [Dashboard] 좌측 슬라이드에서 [Jenkins 관리] 클릭하기

  9. [Dashboard] - [Jenkins 관리] - [Security]에서 [Credentials : Configure creditals] 클릭하기

  10. [Dashboard] - [Jenkins 관리] - [Credentials] - [Stores scoped to Jenkins]에서 System Store의 (global) 오른족의 화살표를 누르고 [Add credentials] 클릭하기

  11. 설정한 환경변수 정보는 [Dashboard] - [Jenkins 관리] - [Credentials] - [System] - [Global credentials (unrestricted)] 에서 확인 가능합니다.

  12. 좌측 상단의 [Dashboard] - [Jenkins 관리]에서 [Jenkins 관리] 클릭하기

  13. [Dahsboard] - [Jenkins 관리] - [System Configuration]에서 [Plugins : Jenkins의 기능을 확장하기 위한 플러그인을 추가, 제거, 사용, 미사용으로 설정할 수 있습니다.] 클릭하기

  14. [Dahsboard] - [Jenkins 관리] - [System Configuration] - [Plugins] - [Available plugins]에서 [NodeJS] 검색 → 선택 후 파란색의 [Install] 버튼 클릭하기

  15. 좌측 상단의 [Dashboard] - [Jenkins]관리에서 [Jenkins 관리] 클릭하기

  16. [Dahsboard] - [Jenkins 관리] - [System Configuration]에서 [Tools : Configure tools, their locations and automatic installers.] 클릭하기

  17. [Dahsboard] - [Jenkins 관리] - [Tools] - [Git installations]를 아래 이미지와 같이 설정하기

    1. 주요 설정값

      1. Name : git

      2. Path to Git Execution : git

      3. Install automatically : 활성화

  18. [Dahsboard] - [Jenkins 관리] - [Tools] - [NodeJS installations]를 아래 이미지와 같이 설정하기

    1. 주요 설정값

      1. Name : node20

      2. Version : NodeJS 20.13.1

      3. Global npm packages to install : yarn@1.22.22

      4. Global npm packages refresh hours : 72

  19. 좌측 상단의 [Dashboard] 클릭하기

  20. 사전에 생성해둔 Pipeline인 [2024-04-cicd-week-6-template] 클릭하기

  21. [Dashboard] - [2024-04-cicd-week-6-template] - [구성] 클릭하기

  22. [Dashboard] - [2024-04-cicd-week-6-template] - [구성] - [Pipeline]을 아래로 교체하기

    1. 주요 설정값

      1. credentialsId 변경 필요

      2. url 변경 필요

    2. 예시

      pipeline {
          agent any
          tools {
              nodejs "node20"
              git "git"
          }
          stages {
              stage('prepare') {
                  steps {
                      echo 'prepare'
                       git branch: "${BRANCH}", credentialsId: "unchaptered", url: 'https://github.com/unchaptered/2024-04-cicd-week-6-template'
                       sh  'ls -al'
                  }
              }
              stage('build') {
                  steps {
                          dir('./'){
                              sh 'ls -al'
                              sh "yarn install"
                              sh "CI=false yarn build"
                      }
                  }
              }
              stage('deploy') {
                  steps {
                      sh "ls -al"
                      echo 'deploy'   
                  }
              }
          }
      }
      

React 배포를 위한 CloudFront, S3 인프라 배포하기

Jenkins 파이프라인 최종 설정하기

  1. AWS EC2 Instance Connect에서 aws-cli 설치하기

    sudo apt install unzip
    
    sudo curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
    
    sudo unzip awscliv2.zip
    
    sudo ./aws/install
  2. AWS EC2 Instance Connect에서 사용자 변경하기

    sudo -s
    su jenkins
  3. AWS EC2 Instance Connect에서 aws profile 설정하기

    aws configure --profile monthly-cs
  4. [Dashboard] - [2024-04-cicd-week-6-template] - [구성] - [Pipeline]을 아래로 교체하기

    1. 주요 설정값

      1. s3://<S3_BUCKET_NAME>

    2. Pipeline

      pipeline {
          agent any
          tools {
              nodejs "node20"
              git "git"
          }
          stages {
              stage('prepare') {
                  steps {
                      echo 'prepare'
                       git branch: "${BRANCH}", credentialsId: "unchaptered", url: 'https://github.com/unchaptered/2024-04-cicd-week-6-template'
                       sh  'ls -al'
                  }
              }
              stage('build') {
                  steps {
                          dir('./'){
                              sh 'ls -al'
                              sh "yarn install"
                              sh "CI=false yarn build"
                      }
                  }
              }
              stage('deploy') {
                  steps {
                          dir('./'){
                              sh 'ls -al'
                              sh "aws s3 sync ./build s3://week6.unchaptered.shop --delete --profile monthly-cs"
                              echo 'deploy done.'   
                      }
                  }
              }
          }
      }

Jenkins 설치하기

Share article
RSSPowered by inblog