IaC/CI CD Tool

4. Github Action (With Matrix Strategy)

Somaz 2024. 3. 12. 20:09
728x90
반응형

Overview

Github Action의 Matrix Strategy에 대해서 알아본다.

2023.05.19 - [IaC/CI CD Tool] - 1. Github Action이란?

 

1. Github Action이란?

Overview 오늘은 Github Action에 대해서 공부해보려고 한다. Github Action이란? GitHub Actions는 빌드, 테스트 및 배포 파이프라인을 자동화할 수 있는 지속적 통합 및 지속적 배포(CI/CD) 플랫폼이다. 리포지

somaz.tistory.com

 

2023.05.22 - [IaC/CI CD Tool] - 2. Github Action 주요 문법(Syntax)

 

2. Github Action 주요 문법(Syntax)

Overview 오늘은 Github Action 문법에 대해서 공부해보려고 한다. 2023.05.19 - [IaC/CI CD Tool] - 1. Github Action이란? 1. Github Action이란? Overview 오늘은 Github Action에 대해서 공부해보려고 한다. Github Action이란? Gi

somaz.tistory.com

 

2023.05.23 - [IaC/CI CD Tool] - 3. Github Action Pull Request 자동화

 

3. Github Action Pull Request 자동화

Overview 오늘은 Pull Request에 대해서 알아본 후 Github Action Pull Request 자동화에 대해서 공부해보려고 한다. 2023.05.19 - [IaC/CI CD Tool] - 1. Github Action이란? 1. Github Action이란? Overview 오늘은 Github Action에 대

somaz.tistory.com

 

mindmap
    root((Matrix Strategy))
        subbranch1[Include]
            incDet[Add additional variables]
        subbranch2[Exclude]
            excDet[Remove specific configurations]
        subbranch3[Fail-Fast]
            ffTrue[true: Cancels remaining tasks if one fails]
            ffFalse[false: All tasks complete regardless of failures]
        subbranch4[Max-Parallel]
            mpDet[Limits concurrent tasks]
        subbranch5[Experimental]
            expTrue[true: Task failure doesn't affect workflow]
            expFalse[false: Used for tasks that are critical]
        subbranch6[One-dimensional Matrix]
        subbranch7[Multidimensional Matrix]
        subbranch8[Utilize Context]
            dynMatrix[Dynamic Matrix Creation]
        subbranch9[Extend/Add/Remove Configurations]
            expScenario[Expansion Scenario Example]

 

 


Matrix Strategy란?

매트릭스 전략을 사용하면 여러 구성에서 작업을 실행할 수 있다. 이는 다양한 운영 체제, 프로그래밍 언어 버전 또는 정의한 기타 변수 집합에서 애플리케이션을 테스트하는 데 특히 유용하다. 매트릭스 전략을 사용하면 워크플로 파일의 중복을 크게 줄이고 다양한 환경에서 더 쉽게 테스트할 수 있다.


 

Matrix Key

  • include
    • 특정 매트릭스 구성에 대한 추가 변수를 추가한다.

 

  • exclude
    • 특정 매트릭스 구성을 제거한다.

 

  • fall-fast
    • true: 하나의 매트릭스 작업이 실패하면 나머지 모든 작업이 취소된다.
    • false : 모든 작업은 작업 실패 여부에 관계없이 완료될 때까지 실행된다.

 

  • max-parallel
    • 동시에 실행되는 작업 수를 제한한다.

 

  • experimental
    • fail-fast와 조합하여 새로운 기능 또는 구성 테스트를 할 때 유용하다.
    • true : Default 설정이다. 작업이 실패하면 중요한 작업이 예상대로 작동하지 않았다는 의미이다.
    • false : 테스트 단계에 있거나 완전히 안정적이지 않은 작업에 사용된다.

 

아래는 모든 Matrix key를 조합하여 만든 Workflow이다.

name: Combined Matrix Strategy Workflow

on: [push]

jobs:
  build-and-test:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: true
      max-parallel: 2
      matrix:
        os: [ubuntu-latest, windows-latest] # macOS is not included in the matrix.
        node-version: [12, 14, 16]
        environment: [staging, production]
        experimental: [false]
        exclude:
          - os: windows-latest
            node-version: 16
        include:
          - node-version: 16
            os: windows-latest
            environment: production
            experimental: true
    continue-on-error: ${{ matrix.experimental }}

    steps:
    - uses: actions/checkout@v2
    - name: Set up Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm install
    - run: npm test

 

  • Workflow Trigger
    • 트리거: 워크플로우는 리포지토리에 대한 푸시 이벤트에 의해 트리거된다.

 

  • Job: Build-and-Test
    • Runs On: 이 작업은 매트릭스 전략을 사용하여 우분투 최신 및 윈도우 최신 두 가지 운영 체제에서 실행된다.

 

  • Strategy Configuration
    • Fail-Fast: true로 설정한다. 매트릭스 내의 작업이 실패하면 매트릭스에서 진행 중이거나 대기열에 있는 다른 작업이 모두 취소된다.
    • Max-Parallel: 병렬로 더 많이 실행될 가능성에 관계없이 동시에 실행되는 작업 수를 2로 제한하여 리소스 사용 또는 작업 간 종속성을 관리한다.
    • Matrix:
      • Operating Systems: ubuntu-latest, windows-latest.
      • Node Versions: 12, 14, 16.
      • Environment: staging, production.
      • Experimental: 초기에는 모든 작업에 대해 false로 설정되며 작업 실패가 워크플로 상태에 영향을 미치는 표준 동작을 나타낸다.

 

  • Matrix Modifications
    • Exclude: Node.js 버전 16이 있는 최신 윈도우에서 실행 중인 작업을 매트릭스에서 제외한다. 이를 통해 실패할 가능성이 있거나 관련이 없는 구성의 실행을 방지할 수 있다.
    • Include: 제외되었거나 처음에 매트릭스의 일부가 아니었던 작업 구성을 명시적으로 추가한다. `experimental: true` 로 표시된 최신 운영 환경에서 Node.js 버전 16을 다시 추가한다. 이 표시를 통해 이 특정 작업이 전체 워크플로 성공 상태에 영향을 주지 않고 실패할 수 있으며 테스트 또는 불안정한 구성에 유용하다.

 

  • Job Steps
    • Checkout: 저장소 코드를 체크아웃하여 작업이 액세스할 수 있도록 허용한다.
    • Setup Node.js: actions/setup-node 작업을 사용하여 매트릭스에 지정된 Node.js 버전(12, 14, 16) 중 하나를 설치하고 환경을 준비한다.
    • NPM Install and Test: `npm install` 을 실행하여 종속성을 설치한 다음 `npm test` 를 실행하여 테스트를 실행한다.

 

  • Continue on Error
    • Conditional Handling: 작업이 `experimental: true` 로 표시되면 작업 실패가 전체 워크플로우를 실패로 표시하지 않으므로 전체 워크플로우 상태에 영향을 주지 않고 안정적인 구성과 함께 실험 또는 진행 중인 구성을 테스트할 수 있다.

 


 

1차원 Matrix

단일 변수를 지정하여 1차원 행렬을 생성할 수 있다. 세 가지 Node.js 버전에서 작업을 실행한다. 매트릭스에 지정된 각 버전에 대해 GitHub Actions는 작업의 별도 인스턴스를 생성하므로 세 가지 버전 모두에서 코드를 병렬로 테스트할 수 있다.

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [12.x, 14.x, 16.x]
    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm install
    - run: npm test

 

 


 

다차원 Matrix

다중 변수를 지정하여 다차원 행렬을 생성할 수 있다. 두 가지 버전의 Node.js(14 및 16)와 두 가지 버전의 데이터베이스(PostgreSQL 12 및 13)를 사용하여 두 운영 체제(Ubuntu 및 Windows)에서 웹 애플리케이션을 테스트할 수 있다.

name: Multidimensional Matrix Workflow

on: [push]

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest]
        node-version: [14.x, 16.x]
        postgres-version: [12, 13]
    steps:
    - uses: actions/checkout@v2
    - name: Set up Node.js
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
    - name: Set up PostgreSQL
      uses: ./.github/actions/setup-postgres
      with:
        postgres-version: ${{ matrix.postgres-version }}
    - run: npm install
    - run: npm test

 

 


 

Context 활용

컨텍스트를 사용하여 GitHub Actions에서 매트릭스를 생성하려면 외부 소스 또는 사전 정의된 변수에서 매트릭스 구성을 동적으로 생성해야 한다. 워크플로 파일에 정적으로 정의되지 않은 조건이나 데이터를 기반으로 매트릭스를 작성하려는 경우 유용하다. GitHub Actions 환경은 YAML 구문만으로는 컨텍스트에서 매트릭스를 동적으로 생성하는 것을 직접 지원하지 않는다. 그러나 작업 조합을 사용하여 출력 매개변수를 설정한 다음 해당 출력을 사용하여 행렬을 정의하면 사용 가능하다.

 

 

2단계 프로세스를 사용하는 일반적인 접근 방식이다.

  1. 매트릭스 구성을 동적으로 생성: 작업을 사용하여 스크립트, API 호출 또는 필요에 맞는 로직을 기반으로 매트릭스 구성을 동적으로 생성할 수 있다. 이 작업의 출력을 매트릭스 구성으로 설정한다.
  2. 후속 작업에서 생성된 매트릭스 사용: 첫 번째 작업의 출력을 참조하여 이에 의존하는 후속 작업에 대한 매트릭스를 정의한다.

 

Dynamic Matrix 생성

간단한 bash 스크립트를 기반으로 행렬을 동적으로 생성하는 방법을 보여준다. 그러나 실제 시나리오에서는 API에서 데이터를 가져오거나, 파일에서 읽거나, 복잡한 논리를 사용할 수 있다.

name: Dynamic Matrix Workflow

on: push

jobs:
  generate-matrix:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
    steps:
      - id: set-matrix
        run: |
          echo "::set-output name=matrix::$(jq -n \\
                  --argjson os '["ubuntu-latest", "windows-latest"]' \\
                  --argjson nodeVersion '[14, 16]' \\
                  '{os: $os, nodeVersion: $nodeVersion}')"

  build-and-test:
    needs: generate-matrix
    runs-on: ${{ matrix.os }}
    strategy:
      matrix: ${{fromJson(needs.generate-matrix.outputs.matrix)}}
    steps:
    - uses: actions/checkout@v2
    - name: Set up Node.js
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.nodeVersion }}
    - run: npm install
    - run: npm test
  • generate-matrix
    • 매트릭스 구성을 생성하는 작업을 담당한다. Bash 스크립트를 사용하여 행렬을 나타내는 JSON 문자열을 생성한다. JSON 문자열은 매트릭스에 포함할 운영 체제와 Node.js 버전을 지정한다. `::set-output name=matrix::` 구문은 이 단계의 출력을 설정한다.

 

  • build-and-test
    • generate-matrix 작업에 따라 달라지며 해당 출력을 사용하여 매트릭스를 정의한다. fromJson() 함수는 출력의 JSON 문자열을 matrix 키워드가 사용할 수 있는 형식으로 변환한다. 그런 다음 작업은 코드 확인, 지정된 버전에 대한 Node.js 설정, 설치 및 테스트 실행으로 진행된다.

 

 


 

Matrix 구성 확장 또는 추가 그리고 제거

매트릭스 구성을 사용하면 include작업 exclude이 실행되는 구성 조합을 세밀하게 제어할 수 있다.

  • Basic Matrix Configuration
    • Operating Systems: ubuntu-latest, windows-latest
    • Python Versions: 3.7, 3.8

 

  • Extend with include
    • 우분투 latest에서 Python 3.9를 테스트하는 작업을 추가하지만, 평가 중임을 나타내기 위해 추가적인 환경 변수 experimental: true를 사용한다.

 

  • Remove with exclude
    • 더 이상 지원되지 않거나 필요하지 않으므로 최신 Windows에서 Python 3.7을 테스트하는 것은 제외한다.
name: Python Library CI

on: [push]

jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest]
        python-version: [3.7, 3.8]
        include:
          - os: ubuntu-latest
            python-version: 3.9
            experimental: true
        exclude:
          - os: windows-latest
            python-version: 3.7
    steps:
      - uses: actions/checkout@v2
      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v2
        with:
          python-version: ${{ matrix.python-version }}
      - run: echo Experimental Flag ${{ matrix.experimental }}
      - run: python -m pip install --upgrade pip
      - run: pip install -r requirements.txt
      - run: pytest

 

다음 매트릭스 조합을 사용하여 초기에 4개의 작업이 생성된다.

  1. ubuntu-latest with Python 3.7
  2. ubuntu-latest with Python 3.8
  3. windows-latest with Python 3.7
  4. windows-latest with Python 3.8

 

After exclude: 최신 Windows에서 Python 3.7을 제거하면 조합이 3개로 줄어든다.

 

After include: Python 3.9과 experimental: true플래그를 사용하여 Ubuntu를 추가하면 다음과 같은 새로운 특정 조합이 추가된다.

  1. ubuntu-latest with Python 3.9 (marked as experimental)

 

따라서 최종조합은 아래와 같다.

  1. ubuntu-latest with Python 3.7
  2. ubuntu-latest with Python 3.8
  3. ubuntu-latest with Python 3.9 (experimental)
  4. windows-latest with Python 3.8

 

Matrix 구성 확장 시나리오

현재 Node.js 버전 12.x 및 14.x로 App을 테스트하고 있으며 테스트 매트릭스의 표준 부분으로 만들기 전에 16.x로 실험적으로 테스트하려고 한다고 가정해 본다.

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [12.x, 14.x]
    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm install
    - run: npm test

 

그리고 워크플로우의 나머지 부분에 영향을 주지 않기 위해 Node.js 16.x에 대한 실험 테스트를 포함시킨다.

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [12.x, 14.x]
        include:
          - node-version: 16.x
    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm install
    - run: npm test

 

App이 Node.js 16.x에서 잘 작동하는지 테스트하고 확인한 후, App을 테스트 매트릭스의 표준 부분으로 만들기로 결정한다. 그런 다음 16.x를 버전 배열에 직접 포함하도록 매트릭스를 업데이트한다.

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [12.x, 14.x, 16.x] # Now including 16.x as a standard version
    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm install
    - run: npm test

 

 

 

 


Reference

https://docs.github.com/en/enterprise-cloud@latest/actions/using-jobs/using-a-matrix-for-your-jobs

728x90
반응형