5. Deployment file image version sync 맞추기

jjuyaa·2023년 4월 17일
0

GitOps

목록 보기
5/7

현재 상황

  1. Dockerfile 을 통해 작성한 application 을 image 로 만들 수 있도록 정의
  2. Github Action Worklfow 를 통해 특정한 trigger 가 발생할 경우 자동으로 작성한 Dockerfile 를 기반으로 이미지를 생성해 image registry 에 push
  3. k8s deployment manifest 를 통해 image registry 에서 이미지를 가져와 Deployment 를 생성한다.

→ 이제 생성한 Deployment 를 k8s 환경에 띄우면 애플리케이션이 실행된다.

💡 ArgoCD 는 helm 으로 감싸진 application 뿐만 아니라 그냥 manifest 도 배포가능하다.

❓ Image Registory 에 새 이미지 버전이 Push 될 경우 deployment manifest 에 작성한 image 의 버전을 어떻게 새로 생성된 이미지로 sync를 맞출 수 있을까?

yaml 파일 수정하는 법

yaml 파일 수정하는 tool : yq

yq 를 설치해 yaml 파일의 key 로 접근해 value 값을 변경할 수 있다.

yq local 에 설치

brew install yq

  • 설치 확인 : yq -V
    replicaCount: 1
    image:
      repository: ghcr.io/cloud-club/gitops-ajaebot
      tag: sha-7fcbb89
      pullPolicy: Always

✔️yaml 파일 key 로 value 값 확인

  • yq '.image.tag' values.yaml : '' 안에 key 작성 ( ! . 부터 시작한다)

✔️yaml 파일 value 값 update

yq -i '.image.tag = "원하는값"' values.yaml

  • ‘’ 내부에 원하는 string 을 “” 으로 감싼다. ( 숫자는 그냥 넣어도 된다.)
  • = 을 통해 원하는 값을 넣을 수 있다.

deployment manifest file 의 image 접근하기

  • deployment.yaml
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: ju-ajae-deployment # deployment 이름
      labels:
        app: ajae-bot
    spec:
      replicas: 1 # pod 1개
      selector:
        matchLabels:
          app: ajae-bot
      template:
        metadata:
          labels:
            app: ajae-bot
        spec: # Pod spec
          containers:
          - name: ajae-container
            image: ghcr.io/juyoung810/slack-bot-test # version 명시 하지 않을 경우 deault 로 `latest` 로 인식한다.
            env: # slackbot token 환경 변수로 넣어주기
              - name: SLACK_BOT_TOKEN
                valueFrom:
                  secretKeyRef:
                    name: juyoung-slack # k8s secret 명
                    key: token
                    optional: false # 반드시 있어야 실행
          imagePullSecrets: # image pull 받기 위한 github token file (secret)
          - name: juyoung-github # github credentials 로 생성한 secret
.spec.template.spec.containers.[0].image
  • containers 필드 아래에는 여러 container 의 설정이 들어갈 수 있으므로 [0] 번째 인덱스의 image 태그임을 명시해준다.

Github action workflow 작성

  • workflow
    ### Update New image version on Deployment manifest file ###
    # manifest file 존재하는 Repository clone and checkout
    - name: Check out my other private repo
      uses: actions/checkout@master
      with:
        repository: juyoung810/slack-bot-config
        token: ${{ secrets.repoPAT  }}
    
    # yq 사용해 yaml file edit
    - name: Change config repo values.yaml
      uses: mikefarah/yq@master
      with:
        cmd: yq -i '.spec.template.spec.containers.[0].image = "${{ steps.meta.outputs.tags }}"' ajae_deployment.yaml
    
    - name: Pushes to config repository
      uses: cpina/github-action-push-to-another-repository@main
      env:
        API_TOKEN_GITHUB: ${{ secrets.repoPAT }}
      with:
        source-directory: "."
        destination-github-username: "juyoung810"
        destination-repository-name: "slack-bot-config"
        user-email: <email>
        target-branch: main
      commit-message: "Change Image version to ${{ steps.meta.outputs.tags }}"

1. 다른 repository checkout

현재 CI 서버에 다른 private repository 를 fetch 해온다.

- name: Check out my other private repo
  uses: actions/checkout@master
  with:
    repository: juyoung810/slack-bot-config
    token: ${{ secrets.repoPAT  }}
  • actions/checkout 모듈을 사용해 나의 다른 private Repository 에 workflow 가 접근할 수 있다.
  • repository : 현재 workflow 에서 접근하고자 하는 repository owner/repository 이름
  • token : repository 를 fetch 해오기 위해 다른 repository 에 접근할 수 있는 권한을 가진 Personal Access Token

Repository 접근 위한 Personal Access Token

  • API_TOKEN_GITHUB 필드에는 다른 repository 에 대한 접근권한을 가진 personal access token 을 repository 의 secret 으로 설정해 workflow 에서 가져와 사용할 수 있다.
  • 기존에 사용한 ${{secrets.GITHUB_TOKEN}} 에는 다른 repository 에 접근할 수 있는 권한이 없으므로 다른 repository 를 관리하는 권한을 가진 repoPAT 이름을 가진 Personal Access Token 을 생성한다.
  • worklow 에서 해당 PAT 을 사용할 수 있도록 repository → Settings → Secrets → Actions 에 들어가 Repository Secrets 로 PAT 을 등록한다.

2. yq 사용해 manifest 파일 수정

# yq 사용해 yaml file edit
- name: Change config repo values.yaml
  uses: mikefarah/yq@master
  with:
    cmd: yq -i '.spec.template.spec.containers.[0].image = "${{ steps.meta.outputs.tags }}"' ajae_deployment.yaml
  • 앞서 살펴본 yq 를 github action module 로 사용할 수 있다.
  • cmd 아래에 하는 명령어를 작성한다.
  • ${{steps.meta.output.tags}} : tag 를 설정할 때 사용한 값. 해당 결과물에 이미지이름/태그가 모두 담겨 있는 것을 로그를 통해 확인할 수 있다.

3. CI 서버에서 변경한 값을 기존 repository 에 push

- name: Pushes to config repository
  uses: cpina/github-action-push-to-another-repository@main
  env:
    API_TOKEN_GITHUB: ${{ secrets.repoPAT }}
  with:
    source-directory: "."
    destination-github-username: "juyoung810"
    destination-repository-name: "slack-bot-config"
    user-email: <사용자 email>
    target-branch: main
    commit-message: "Change Image version to ${{ steps.meta.outputs.tags }}"
  • 이전에 생성한 다른 repo 에 접근 가능한 PersonalAccessTokenAPI_TOKEN_GITHUB 이름의 환경변수로 넣어준다.
  • 현재 작업 중인 directory 의 변경사항을 destination-github-username / destination-repository-name 에 push 해준다.
  • user-emailAPI_TOKEN_GITHUB 를 통해 git config 인증이 된다.
  • target-branchcommit-message 로 commit & push 된다.

결과

새로 생성된 image

config repository

  • config repository 에 있는 manifest file 의 image version 이 변경됨
  • 작성한 commit message 를 확인할 수 있다.

참고

GitHub - mikefarah/yq: yq is a portable command-line YAML, JSON, XML, CSV and properties processor

GitHub Actions의 체크아웃(Checkout) 액션으로 코드 내려받기

GitHub - actions/checkout: Action for checking out a repo

GitHub Action

Welcome to github-action-push-to-another-repository's documentation! - github-action-push-to-another-repository documentation

push-to-another-repository-example/ci.yml at main · cpina/push-to-another-repository-example

0개의 댓글