首页 > 解决方案 > GitHub 操作:使用不同的环境值重复步骤

问题描述

我刚刚创建了我的第一个 GitHub 操作工作流,它处理 Docker 图像。它基本上看起来像这样:

name: My Name
on: workflow_dispatch

jobs:
  whatever:
    runs-on: ubuntu-latest
    steps:
      - env:
          TARGET_DOCKER_IMAGE: node
          TARGET_TAG: 14-alpine
        run: |
            # ... ca 20 lines of code which reference ${TARGET_DOCKER_IMAGE} and ${TARGET_TAG}
        

现在,我意识到我希望我的操作不仅仅针对node:14-alpine图像,还针对其他几个图像。当然,我希望避免复制和粘贴代码。所以,我基本上需要重复相同的步骤,但使用不同的env值。我怎么做?

标签: github-actions

解决方案


您可以使用matrix strategy. 请在下面的例子中罚款,

jobs:
  whatever:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        TAG: [14-alpine, slim, buster, latest]
    steps:
      - env:
          TARGET_DOCKER_IMAGE: node
          TARGET_TAG: ${{ matrix.TAG }}
        run: |
            # ... ca 20 lines of code which reference ${TARGET_DOCKER_IMAGE} and ${TARGET_TAG}

下面还有一个例子,推送到多个 ECR 存储库

jobs:
  build-app:
  runs-on: ubuntu-latest
  strategy:
      matrix:
        Repo: [Repo1, Repo2, Repo3]
    steps:
    # see: https://github.com/aws-actions/configure-aws-credentials
    - name: Configure AWS Credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        aws-region: us-east-1

    # see: https://github.com/aws-actions/amazon-ecr-login
    - name: Log in to Amazon ECR
      id: login-ecr
      uses: aws-actions/amazon-ecr-login@v1

    - name: Build, tag, and push image to Amazon ECR
      env:
        ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
        ECR_REPOSITORY:  ${{ matrix.Repo }}
        IMAGE_TAG: ${{ github.sha }}
      run: |
        docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
        docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG

推荐阅读