Phoenix 앱에 대한 기본 Github 작업 설정

26589 단어 cigithubelixirphoenix
개인 Phoenix 서버에 대한 CI/CD(지속적인 통합 및 지속적인 배포) 설정을 보류했습니다. 그러고 보니 생각보다 훨씬 쉬웠다. 오늘은 나중에 참고할 수 있도록 배운 내용을 간략하게 작성하겠습니다. CI/CD 플랫폼으로 Github Actions을 사용했습니다. 개념을 쉽게 소화할 수 있도록 패턴 4개를 만들었습니다.

にほんご

A: 간단한 피닉스 테스트





최소한의 간단한 예는 erlef/setup-beam의 저장소에서 찾을 수 있습니다. 워크플로우 YAML 파일을 생성하고 예제 워크플로우에 붙여넣은 .github/workflows 디렉토리를 만들기만 하면 되었습니다. forkflow YAML 파일은 .github/workflows/ci.yml 와 같이 원하는 이름을 지정할 수 있습니다.

on: push

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      db:
        image: postgres:latest
        ports: ['5432:5432']
        env:
          POSTGRES_PASSWORD: postgres
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
    steps:
      - uses: actions/checkout@v2
      - uses: erlef/setup-beam@v1
        with:
          otp-version: '22.2'
          elixir-version: '1.9.4'
      - run: mix deps.get
      - run: mix test


이것은 훌륭하고 간단하며 작은 Phoenix 앱에 충분할 수 있지만 한 가지 문제는 실행될 때마다 종속성을 설치해야 한다는 것입니다. 작은 Phoenix 앱의 경우에도 워크플로를 완료하는 데 몇 분 정도 걸릴 수 있습니다. 따라서 종속성을 캐시하는 것이 좋습니다.

B: 캐싱 사용





이것은 사전 정의된 작업actions/cache이며 an example for Elixir . 의존성 및 빌드를 설치skip하기 위해 "종속성 설치"단계에서 if: steps.mix-cache.outputs.cache-hit != 'true' 절을 사용합니다. 우리는 Linux-23.3.1-1.11.3-35a9 필드에 더 많은 버전을 추가할 수 있도록 otp 버전과 matrix와 같은 Elixir 버전을 포함하는 캐시 키를 사용합니다.

on: push

jobs:
  dependencies:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        elixir: ['1.11.3']
        otp: ['23.3.1']
    steps:
      - name: Cancel previous runs
        uses: styfle/[email protected]
        with:
          access_token: ${{ github.token }}
      - name: Checkout Github repo
        uses: actions/checkout@v2
      - name: Sets up an Erlang/OTP environment
        uses: erlef/setup-beam@v1
        with:
          elixir-version: ${{ matrix.elixir }}
          otp-version: ${{ matrix.otp }}
      - name: Retrieve cached dependencies
        uses: actions/cache@v2
        id: mix-cache
        with:
          path: |
            deps
            _build
          key: ${{ runner.os }}-${{ matrix.otp }}-${{ matrix.elixir }}-${{ hashFiles('mix.lock') }}
      - name: Install dependencies
        if: steps.mix-cache.outputs.cache-hit != 'true'
        run: |
          mix local.rebar --force
          mix local.hex --force
          mix deps.get
          mix deps.compile

  mix-test:
    needs: dependencies
    runs-on: ubuntu-latest
    strategy:
      matrix:
        elixir: ['1.11.3']
        otp: ['23.3.1']
    services:
      db:
        image: postgres:latest
        ports: ['5432:5432']
        env:
          POSTGRES_PASSWORD: postgres
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
    steps:
      - name: Cancel previous runs
        uses: styfle/[email protected]
        with:
          access_token: ${{ github.token }}
      - name: Checkout Github repo
        uses: actions/checkout@v2
      - name: Sets up an Erlang/OTP environment
        uses: erlef/setup-beam@v1
        with:
          elixir-version: ${{ matrix.elixir }}
          otp-version: ${{ matrix.otp }}
      - name: Retrieve cached dependencies
        uses: actions/cache@v2
        id: mix-cache
        with:
          path: |
            deps
            _build
          key: ${{ runner.os }}-${{ matrix.otp }}-${{ matrix.elixir }}-${{ hashFiles('mix.lock') }}
      - run: mix test --trace --slowest 10


actions/cache을 추가하는 것 외에 각 단계를 설명하는 이름을 지정했습니다. 또한 유용한 추가 정보를 얻을 수 있도록 --trace 명령에 --slowest 10mix test 옵션을 추가합니다.

C: 정적 코드 분석 사용





이제 캐싱을 활용하는 효율적이고 빠른 워크플로우가 있으므로 더 많은 것을 병렬로 실행할 수 있습니다. 정적 코드 분석이 있으면 좋을 것입니다. Pierre-Louis Gottfrois의 이 게시물Github actions for Elixir & Phoenix app with cache에는 이에 대한 좋은 예가 있습니다. Bacially 우리는 credo와 dialyxir를 설치하고 작업 흐름에서 실행합니다. dialyxir는 특히 완료하는 데 10분이 걸릴 수 있지만 결과가 캐시되면 종속성이 변경되지 않는 한 빠릅니다.

CI 구성을 편집하기 전에 mix.exs 파일에 credo 및 dialyxir를 추가한 다음 평상시처럼 mix deps.get를 실행합니다.

 defmodule Mnishiguchi.MixProject do
   use Mix.Project

   ...

   defp deps do
     [
       {:phoenix, "~> 1.5.7"},
       ...
+      {:credo, "~> 1.4", only: [:dev, :test], runtime: false},
+      {:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}
     ]
   end

   ...


다음은 업데이트된 워크플로 파일입니다.

on: push

jobs:
  dependencies:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        elixir: ['1.11.3']
        otp: ['23.3.1']
    steps:
      - name: Cancel previous runs
        uses: styfle/[email protected]
        with:
          access_token: ${{ github.token }}
      - name: Checkout Github repo
        uses: actions/checkout@v2
      - name: Sets up an Erlang/OTP environment
        uses: erlef/setup-beam@v1
        with:
          elixir-version: ${{ matrix.elixir }}
          otp-version: ${{ matrix.otp }}
      - name: Retrieve cached dependencies
        uses: actions/cache@v2
        id: mix-cache
        with:
          path: |
            deps
            _build
            priv/plts
          key: ${{ runner.os }}-${{ matrix.otp }}-${{ matrix.elixir }}-${{ hashFiles('mix.lock') }}
      - name: Install dependencies
        if: steps.mix-cache.outputs.cache-hit != 'true'
        run: |
          mkdir -p priv/plts
          mix local.rebar --force
          mix local.hex --force
          mix deps.get
          mix deps.compile
          mix dialyzer --plt

  static-code-analysis:
    needs: dependencies
    runs-on: ubuntu-latest
    strategy:
      matrix:
        elixir: ['1.11.3']
        otp: ['23.3.1']
    steps:
      - name: Cancel previous runs
        uses: styfle/[email protected]
        with:
          access_token: ${{ github.token }}
      - name: Checkout Github repo
        uses: actions/checkout@v2
      - name: Sets up an Erlang/OTP environment
        uses: erlef/setup-beam@v1
        with:
          elixir-version: ${{ matrix.elixir }}
          otp-version: ${{ matrix.otp }}
      - name: Retrieve cached dependencies
        uses: actions/cache@v2
        id: mix-cache
        with:
          path: |
            deps
            _build
            priv/plts
          key: ${{ runner.os }}-${{ matrix.otp }}-${{ matrix.elixir }}-${{ hashFiles('mix.lock') }}
      - run: mix format --check-formatted
      - run: mix credo
      - run: mix dialyzer --no-check --ignore-exit-status

  mix-test:
    runs-on: ubuntu-latest
    needs: dependencies
    strategy:
      matrix:
        elixir: ['1.11.3']
        otp: ['23.3.1']
    services:
      db:
        image: postgres:latest
        ports: ['5432:5432']
        env:
          POSTGRES_PASSWORD: postgres
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
    steps:
      - name: Cancel previous runs
        uses: styfle/[email protected]
        with:
          access_token: ${{ github.token }}
      - name: Checkout Github repo
        uses: actions/checkout@v2
      - name: Sets up an Erlang/OTP environment
        uses: erlef/setup-beam@v1
        with:
          elixir-version: ${{ matrix.elixir }}
          otp-version: ${{ matrix.otp }}
      - name: Retrieve cached dependencies
        uses: actions/cache@v2
        id: mix-cache
        with:
          path: |
            deps
            _build
            priv/plts
          key: ${{ runner.os }}-${{ matrix.otp }}-${{ matrix.elixir }}-${{ hashFiles('mix.lock') }}
      - run: mix test --trace --slowest 10


D: 배포 포함





이것은 선택 사항이지만 Phoenix 앱을 Gigalixir에 배포하므로 CI 프로세스 후에 배포를 자동화할 수 있으면 좋을 것입니다. Elixir/PhoenixアプリをGitHub ActionsでGigalixirに継続的デプロイする님의 이 게시물@mokichi은 정말 훌륭했습니다. 그는 설정이 매우 간단하여 타사 라이브러리가 전혀 필요하지 않다고 지적합니다.

기본 아이디어는 Gigalixir의How to Set Up Continuous Integration (CI/CD)? 설명서에 설명되어 있습니다.

name: CI/CD
on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

jobs:
  dependencies:
    ...

  static-code-analysis:
    ...

  mix-test:
    ...

  deploy:
    needs:
      - static-code-analysis
      - mix-test
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Github repo
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Deploy to Gigalixir
        run: |
          git remote add gigalixir https://${{ secrets.GIGALIXIR_EMAIL }}:${{ secrets.GIGALIXIR_API_KEY }}@git.gigalixir.com/${{ secrets.GIGALIXIR_APP_NAME }}.git
          git push -f gigalixir HEAD:refs/heads/master



세 개의 비밀 값( GIGALIXIR_EMAIL , GIGALIXIR_API_KEYGIGALIXIR_APP_NAME )에 대해 프로젝트의 Github 저장소에서 할당할 수 있습니다. Github의 Creating encrypted secrets for a repository 설명서에 설명되어 있습니다. GIGALIXIR_EMAIL 환경 변수의 경우 URI 인코딩이 필요합니다. foo%40gigalixir.com .

할 것:
  • 데이터베이스 마이그레이션

  • 그게 다야!

    좋은 웹페이지 즐겨찾기