GitHub CI 基于不同分支推送构建和推送到不同ECR的脚本

GitHub CI script for build and push to different ECR based on differenct branch push

我在 GitHub 上有一个项目,我想设置 CI 作业来构建 docker 图像并推送到 AWS ECR。我的要求是 -

  1. 一个ci文件(我创建了.github/workflows/aws.yml
  2. CI 作业必须仅在推送到主分支和沙箱分支时触发
  3. 如果推送到沙箱分支,则 docker 图像应推送 ECR1
  4. 如果推送到 master 分支,那么 docker 图像应该被推送到 ECR2

到目前为止,我已经制作了以下 CI 文件

.github/workflows/aws.yml -

  name: CI

  on:
    pull_request:
      branches:
      - master
      - sandbox
    push:
      branches:
      - master
      - sandbox

  env:
    AWS_REPOSITORY_URL_MASTER: ${{ secrets.AWS_REPOSITORY_URL_MASTER }}
    AWS_REPOSITORY_URL_SANDBOX: ${{ secrets.AWS_REPOSITORY_URL_SANDBOX }}
    AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
    AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

  jobs:
    build-and-push:
      name: Build and push image to AWS ECR master
      runs-on: ubuntu-latest
      steps:

      - name: Checkout
        uses: actions/checkout@v2

      - name: Setup ECR
        run: $( aws ecr get-login --no-include-email --region ap-south-1)

      - name: Build and tag the image
        run: docker build -t $AWS_REPOSITORY_URL_MASTER .

      - name: Push
        run: docker push $AWS_REPOSITORY_URL_MASTER
    build-and-push-sandbox:
      name: Build and push image to AWS ECR master
      runs-on: ubuntu-latest
      steps:

      - name: Checkout
        uses: actions/checkout@v2

      - name: Setup ECR
        run: $( aws ecr get-login --no-include-email --region ap-south-1)

      - name: Build and tag the image
        run: docker build -t $AWS_REPOSITORY_URL_SANDBOX .

      - name: Push
        run: docker push $AWS_REPOSITORY_URL_SANDBOX

脚本如何区分何时 运行 build-and-push-master(在主分支推送时触发)和 build-and-push-sandbox(在沙箱分支推送时触发)?

job 级别添加一个 if 子句:

jobs:
    build-and-push:
      name: Build and push image to AWS ECR master
      runs-on: ubuntu-latest
      if: github.ref == 'refs/heads/master'
      steps:

    build-and-push-sandbox:
      name: Build and push image to AWS ECR sandbox
      runs-on: ubuntu-latest
      if: github.ref == 'refs/heads/sandbox'
      steps:

或者,由于作业非常相似,您可以尝试统一它们并将环境变量 $AWS_REPOSITORY 设置为 ${{ secrets.AWS_REPOSITORY_URL_MASTER }}${{ secrets.AWS_REPOSITORY_URL_SANDBOX }},具体取决于 github.ref.