배경지식 쌓기 - Github Actions

CI/CD

Posted by Yan on September 9, 2022

github action

  • 코드를 push하면 github.com에서 컴퓨터를 하나 빌려주는데, 이것이 runner다.
  • 내 코드의 로직은 아무것도 없는 runner라는 가상머신에서 실행되면서 테스트나 deploy, 메세지 등의 처리를 할 수 있게 된다.

구조

아래 4가지로 구성되어 있는데, 각 컴포넌트는 하위 단계를 포함한다.

  1. Workflow
  2. Job
  3. Step
  4. Action

actions의 yml 파일

  • github repo의 action tab에서 action을 생성하면 해당 레포의 .github 디렉토리가 생기고, workflows/main.yml을 만드는 구조다.
  • main.yml의 내용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# This is a basic workflow to help you get started with Actions

name: CI

# Controls when the workflow will run
on:
  # Triggers the workflow on push or pull request events but only for the "main" branch
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v3

      # Runs a single command using the runners shell
      - name: Run a one-line script
        run: echo Hello, world!

      # Runs a set of commands using the runners shell
      - name: Run a multi-line script
        run: |
          echo Add other actions to build,
          echo test, and deploy your project.
  • on : push 혹은 pull request시 (event의 타입) 어떤 액션이 일어날 건지 정의하기 (ex. on: issues: types: )
  • runs-on : 어떤 가상머신에서 구동할 건지.
    • ubuntu-latest : 가장 최근의 우분투 머신
  • stepsname: action의 이름
  • stepsrun: 실행할 명령어
  • usesactions/checkout@v3 : github.com/actions/checkoutcheckout이라는 actions의 레포가 있는데, 이는 github에서 만든 것이다. 이렇게 다른 유저가 만든 액션을 이렇게 가져다가 쓸 수 있다.
    • runner는 기본적으로 아무것도 안 들어있는 가상머신인데, actions/checkout 레포를 clone받아서 그 다음 step들을 사용할 수 있게 하는 명령어다.]

환경변수

  • 환경변수를 저장하고 사용할 수 있다.
1
2
3
4
- name: "context"
  env: 
    COMMIT_ID: $
  run: echo "Commit id => $COMMIT_ID"
  • settings - secrets - actions에서 password 같은 비밀 정보를 저장하여 사용할 수 있다. 물론 echo로 프린트해도 password는 나타나지 않게 설정되어있다.
1
2
3
4
- name: Print Password
  env: 
    MY_PASSWORD: $
  run: echo My password is $MY_PASSWORD

OS종류, 언어 별 버전 관리

매트릭스 빌드 : 여러 타겟을 동시에 빌드하는 것

  • 예시: 1개의 Job에서 4개의 빌드 아티팩트로 매트릭스 빌드 하기
    • (1)os: ubuntu-lates, node: 12.x
    • (2)os: ubuntu-lates, node: 14.x
    • (3)os: windows-2016, node: 12.x
    • (4)os: windows-2016, node: 14.x
1
2
3
4
strategy:
  matrix:
    os: [ubuntu-lates, windows-2016]
    node-version: [12.x, 14.x]

build job과 test job 분리하기

  • jobs와 test를 따로 쓰면 된다. 그런데 아티팩트를 찾을 수 없다는 에러가 나오게 될 것이다.
  • 이때 Built-in 아티팩트 스토리지를 이용한다.
  • 아티팩트란?
    • 워크플로우의 잡들 사이에서 데이터를 공유하게 해주는 것이다. 그리고 워크프롤우가 완료되고 나면 데이터를 저장하게 해준다.
    • 잡이 완료된 후에도 데이터를 유지할 수 있게 해주는 것이다.
    • 워크플로우 실행 중 생산된 파일과 파일의 컬렉션이다.
    • 잡 중간에 아티팩트를 사용하여 데이터를 통과시킬 수 있으며, 워크플로우 실행이 끝난 뒤에도 빌드 혹은 테스트 결과를 보존할 수 있다.
    • 깃허브는 upload와 download 두 가지 액션을 제공한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
name: action의 이름
on: pull_request_review
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
          - uses: actions/checkout@v3
          - name: npm install and build webpack
            run: |
              npm install
              npm run build
          - uses: actions/upload-artifact@master
            with:
              name: webpack artifacts
              path: public/
          - name: Label approved pull requests
            uses: abinoda/label-when-approved-action@1.0.5
            env:
              APPROVALS: "1"
              GITHUB_TOKEN: $
              ADD_LABEL: "approved"
  test:
    needs: build
    runs-on: ubuntu-latest
    strategy:
      matrix:
        os: [ubuntu-lates, windows-2016]
        node-version: [12.x, 14.x]
    steps:
          - uses: actions/checkout@v3
          - uses: actions/download-artifact@master
            with:
              name: webpack artifacts
              path: public
          - name: Use Node.js $
            uses: actions/setup-node@v1
            with:
              node-versions: $
          - name: npm install and test
            run: |
              npm install
              npm test
            env: 
              CI : true
  • test수행 전 built-in 스토리지에 업로드해뒀던 아티팩트를 다운로드해서 테스트를 수행하는 방법
    • 아티팩트 스토리지 업로드
    1
    2
    3
    4
    
    - uses: actions/upload-artifact@master
      with:
        name: webpack artifacts
        path: public/
    
    • 아티팩트 스토리지 다운로드
    1
    2
    3
    4
    
    - uses: actions/download-artifact@master
      with:
        name: webpack artifacts
        path: public
    
    • build 하는 vm과 test하는 vm이 종속적으로 돌아가도록 하는 방법: 빌드가 끝난 다음에만 테스트 파일이 돌아가도록 명시하기
    1
    2
    3
    
    test:
      needs: build
      runs-on: ubuntu-latest
    

PR에 자동으로 label 붙이기

  • 자동으로 approved label 붙이기: market place에서 Label approved Pull request 사용
1
2
3
4
5
6
- name: Label approved pull requests
  uses: abinoda/label-when-approved-action@1.0.5
  env:
    APPROVALS: "1"
    GITHUB_TOKEN: $
    ADD_LABEL: "approved"
  • market place에서 label commenter를 사용하면 bot이 자동으로 PR의 label에 따라 comment를 달아줄 수 있다.
예시
  • commit message를 이용해 업무일지를 자동으로 쓸 수 있게 한다면?
reference

생활코딩 - github.com-action
GitHub Actions로 개발 주기 자동화 - 엄지혜 | 애저 듣고보는 잡학지식
아티팩트를 사용하여 워크플로우 데이터 유지하기