43

Is there a DRY way to calculate and share a value in multiple job steps with Github Actions?

In the below workflow yml file, echo ${GITHUB_REF} | cut -d'/' -f3`-${GITHUB_SHA} is repeated in multiple steps.

name: Test, Build and Deploy
on:
  push:
    branches:
      - master
jobs:
  build_and_push:
    name: Build and Push
    runs-on: ubuntu-latest
    steps:
      - name: Docker Build
        uses: "actions/docker/cli@master"
        with:
          args: build . --file Dockerfile -t cflynnus/blog:`echo ${GITHUB_REF} | cut -d'/' -f3`-${GITHUB_SHA}
      - name: Docker Tag Latest
        uses: "actions/docker/cli@master"
        with:
          args: tag cflynnus/blog:`echo ${GITHUB_REF} | cut -d'/' -f3`-${GITHUB_SHA} cflynnus/blog:latest
4

1 回答 1

69

set-output可用于定义步骤的输出。然后可以在后面的步骤中使用输出,并在with输入env部分进行评估。

以下是您的示例的样子。

name: Test, Build and Deploy
on:
  push:
    branches:
      - master
jobs:
  build_and_push:
    name: Build and Push
    runs-on: ubuntu-latest
    steps:
      - name: Set tag var
        id: vars
        run: echo ::set-output name=docker_tag::$(echo ${GITHUB_REF} | cut -d'/' -f3)-${GITHUB_SHA}
      - name: Docker Build
        uses: "actions/docker/cli@master"
        with:
          args: build . --file Dockerfile -t cflynnus/blog:${{ steps.vars.outputs.docker_tag }}
      - name: Docker Tag Latest
        uses: "actions/docker/cli@master"
        with:
          args: tag cflynnus/blog:${{ steps.vars.outputs.docker_tag }} cflynnus/blog:latest

这是另一个示例,展示了如何动态设置要由操作使用的多个变量。

      - name: Set output variables
        id: vars
        run: |
          echo ::set-output name=pr_title::"[Test] Add report file $(date +%d-%m-%Y)"
          echo ::set-output name=pr_body::"This PR was auto-generated on $(date +%d-%m-%Y) \
            by [create-pull-request](https://github.com/peter-evans/create-pull-request)."
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v2
        with:
          title: ${{ steps.vars.outputs.pr_title }}
          body: ${{ steps.vars.outputs.pr_body }}

或者,您可以创建环境变量。

      - name: Set environment variables
        run: |
          echo "PR_TITLE=[Test] Add report file $(date +%d-%m-%Y)" >> $GITHUB_ENV
          echo "PR_BODY=This PR was auto-generated on $(date +%d-%m-%Y) by [create-pull-request](https://github.com/peter-evans/create-pull-request)." >> $GITHUB_ENV
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v2
        with:
          title: ${{ env.PR_TITLE }}
          body: ${{ env.PR_BODY }}

更新:第一个示例中的 docker 操作已弃用。有关在 GitHub Actions 中使用 docker 的最新方法,请参阅此答案

注意:对于不同工作之间的共享价值,请参阅此问题

于 2019-09-18T09:09:16.907 回答