Cloud Wave

CI/CD ON EKS

ankisile 2023. 10. 15. 13:20

cicd on eks

CI/CD

CI란?

  • 지속적인 통합(Continuous Integration)
  • 빌드/테스트 자동화 과정
  • 새로운 코드 변경 사항이 정기적으로 빌드 및 테스트 되어 공유 레포지토리에 통합히는 것을 의미
  • 커밋할 때마다 빌드와 일련의 자동 테스트가 이루어져 동작을 확인하고 변경으로 인해 문제가 생기는 부분이 없도록 보장

CD란?

  • 지속적인 서비스 제공(Continuous Deliver) / 지속적인 배포(Continuous Deployment)
  • 배포 자동화 과정
  • 개발자의 변경 사항이 레포지토리를 넘어, 고객의 프로덕션(Production) 환경까지 릴리즈 되는 것
  • 간단한 코드 변경이 정기적으로 마스터에 커밋되고, 자동화된 빌드 및 테스트 프로세스를 거치며 다양한 사전 프로덕션 환경으로 승격되며, 문제가 발견되지 않으면 최종적으로 배포

Github Action이란

GitHub Actions는 GitHub에서 제공하는 서비스로, 빌드, 테스트, 배포 파이프라인을 자동화할 수 있는 CI(Continuous Integration, 지속 통합)와 CD(Continuous Deployment, 지속 배포) 플랫폼

GitHub Actions를 사용하면 GitHub 리포지토리에서 손쉽게 CI/CD 결과를 확인하고 관리가능

YAML 포맷을 사용하여 가독성이 높고, 이미 구현되어 있는 수많은 액션을 활용하여 간단하게 CI/CD 플로우를 작성 가능

Github Actions 사용한 이유

GitHub 페이지에서 바로 빌드 결과를 확인/실행하고 여러 페이지를 오갈 필요가 없음

커스텀 액션을 통해 워크플로 파일을 간단히 유지하면서도 빌드 과정에서 원하는 동작을 쉽게 사용 가능

ArgoCD란

- GitOps를 구현하기 위한 도구 중 하나로 Kubernetes 애플리케이션의 자동 배포를 위한 오픈소스 도구

ArgoCD를 쓰는 이유 → GitOps

- GitOps의 핵심은 Git 저장소에 저장된 쿠버네티스 매니페스트 같은 파일을 이용하여, 배포를 선언적으로 한다는 것. 즉, Git에 저장된 매니페스트가 쿠버네티스 클러스터에도 똑같이 반영됨

- 이러한 방법은 이해하기 쉬운 운영 모델을 제공하며, Git을 사용하기 때문에 보안 및 감사 기능도 기본으로 제공된다 그리고 재해로부터 쉽게 복구할 수 있다. 무엇보다도 큰 장점은 개발자 친화적이다.

- 쿠버네티스의 주요한 개념 중 하나는 선언적 시스템→ 어떠한 리소스를 생성하라 명령하는 것이 아니라, 사용자는 매니페스트를 정의하고, 시스템은 그 상태를 유지하기 위해 노력한다는 것

이런 점이 상당히 유사하기 때문에 ArgoCD 사용

Github Action

seoul에 대한 ci/cd

name: Build and Deploy to Dev

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
    env: 
      working-directory: ./
      APPLICATION: ${{secrets.SEOULAPPLICATION}}
    steps:
      - name: ✨Checkout code
        uses: actions/checkout@v2
      - name: ✨Set up Java
        uses: actions/setup-java@v2
        with:
          distribution: 'adopt'
          java-version: '11'
      - name: ✨Copy application.properties
        run: |
          mkdir ./src/main/resources
          touch ./src/main/resources/application.properties
          echo "${{env.APPLICATION}}" > ./src/main/resources/application.properties
      - uses: actions/upload-artifact@v2
        with:
          name: application.properties
          path: ./src/main/resources/application.properties
      - name: ✨Grant execute permission gradlew
        run: chmod +x gradlew
        working-directory: ${{env.working-directory}}
      - name: ✨Build with gradle
        run: ./gradlew clean build
        working-directory: ${{env.working-directory}}
      - name: ✨Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-region: ap-northeast-2
          role-to-assume: ${{ secrets.ROLE_TO_ASSUME }}   
      - name: ✨Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v1
      - name: ✨Set short sha
        id: sha_short
        run: echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
      - name: ✨Build, tag, and push image to Amazon ECR
        id: build-image
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          ECR_REPOSITORY: eu-central-repository
          IMAGE_TAG: ${{ steps.sha_short.outputs.sha_short }}
        run: |
          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
          echo "::set-output name=image::$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG"
      - name: 🧨 Checkout
        uses: actions/checkout@v3
        with:
          repository: 'ankisile/Cloudwave-Project-CD'
          token: ${{ secrets.TOKEN_GITHUB }}
      - name: 🧨 Change Docker tag
        run: |
          sed -i "s/seoul-repository:.*/seoul-repository:${{ steps.sha_short.outputs.sha_short }}/g" ./seoul/cloudwave-was.yamlcloudwave-was.yaml
          git config --global user.email "ankisile@gmail.com"
          git config --global user.name "ankisile"
          git commit -am "triggered by github action"
          git push origin "main"

ArgoCD

ArgoCD 설치

네임 스페이스 생성

$ kubectl create ns argocd
$ kubectl apply -n argocd \
-f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
$ kubectl get all -n argocd

ArgoCD CLI 설치

VERSION=$(curl --silent "https://api.github.com/repos/argoproj/argo-cd/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
sudo curl --silent --location -o /usr/local/bin/argocd https://github.com/argoproj/argo-cd/releases/download/$VERSION/argocd-linux-amd65
sudo chmod +x /usr/local/bin/argocd

ArgoCD 외부에서 접속하도록 로드 밸런서 이용

kubectl patch svc argocd-server -n argocd -p '{"spec":{"type":"LoadBalancer"}}'

LB 생성

export ARGOCD_SERVER=`kubectl get svc argocd-server -n argocd -o json | jq --raw-output.status.loadBalancer.ingress[0].hostname`

ArgoCD의 암호

ARGO_PWD=`kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}"|base64 -d`

admin으로 로그인

argocd login $ARGOCD_SERVER --username admin --password $ARGO_PWD --insecure

웹으로 접속 확인

echo $ARGOCD_SERVER

Settings에서 Repositories로 들어간다.

Connect Repo를 클릭한다

  1. Connect Repo를 클릭하면 다음과 같은 화면이 뜬다.
  2. Repository URL에는 쿠버네티스에서 사용할 YAML 파일이 있는 GITHUB URL를 적어주어야 한다.
  3. Password는 다음과 같이 발급

-  setting에 들어간다.

- Developer Setting에 들어간다.

- 왼쪽 메뉴에서 토큰을 누른다

- 우상단에서 Genereate new token을 누르고 classic으로 발급받는다

 

- 다음과 같이 설정하고 발급하면 token값이 나온다. 그 토큰 값을 복사해서 ArgoCD의 password값에 넣어줘야 한다.

- 성공적으로 git과 연결되었으면 다음과 같이 뜬다.

이제 Application을 만들어보자

new app을 선택하면 다음과 같은 화면이 나온다.

  • Application Name ⇒ ArgoCD에서의 application name을 작성한다
  • Project Name ⇒ default
  • Repository URL ⇒ 위의 setting에서 등록시킨 url이 자동으로 뜬다. 그 github의 url을 넣어주면 된다
  • Path ⇒ github 레포지토리에서 배포할 yaml파일이 있는 위치를 적어주면 된다. 가장 상위에 있으면 . 을 적으면 된다
  • Cluster URL ⇒ Cluster의 URL이 자동으로 생성된다(https://kubernetes.default.svc 를 넣어주면 된다)
  • Namespace ⇒ 쿠버네티스 클러스터에서 배포할 namespace를 작성해준다

 

잘 되었으면 다음과 같이 잘 뜨는것을 확인 할 수 있다. 와!

 

에러

github action 에서의 error

  1. Setup-Java 단계에서 에러As part of the v2 release, setup-java now requires a mandatory distribution argument and no longer supports legacy Java version syntax 1.x. You can use our migration guide to learn more about upgrading to v2.
  2. steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v2 with: distribution: 'adopt' java-version: '11' - run: java -cp java HelloWorldApp
  3. ⇒ actions/setup-java@v2 는 distribution argument가 필수다. 따라서, distribution argument를 작성해줘야 한다.
  4. https://github.blog/changelog/2021-04-05-github-actions-setup-java-now-support-adopt-openjdk/

 

 

참고자료

https://velog.io/@hsshin0602/운송장-정보보호-서비스-EKS-Github-Action-연동

실습2-7. AWS EKS- ArgoCD (brunch.co.kr)

https://tech.kakaoenterprise.com/180