Github操作,如何在作业步骤之间共享计算值?



有没有一种 DRY 方法可以使用 Github Actions 在多个作业步骤中计算和共享值?

在下面的工作流 yml 文件中,echo ${GITHUB_REF} | cut -d'/' -f3'-${GITHUB_SHA}分多个步骤重复。

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
set-output

可用于定义步骤的输出。然后可以在后续步骤中使用输出,并在withenv输入部分中进行评估。此外,返回输出的阶跃应该有一个id,它由消耗输出的步长引用。

下面是您的示例的外观。

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 "docker_tag=$(echo ${GITHUB_REF} | cut -d'/' -f3)-${GITHUB_SHA}" >> $GITHUB_OUTPUT
- 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: |
pr_title="[Test] Add report file $(date +%d-%m-%Y)"
pr_body="This PR was auto-generated on $(date +%d-%m-%Y) 
by [create-pull-request](https://github.com/peter-evans/create-pull-request)."
echo "pr_title=$pr_title" >> $GITHUB_OUTPUT
echo "pr_body=$pr_body" >> $GITHUB_OUTPUT
- name: Create Pull Request
uses: peter-evans/create-pull-request@v4
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@v4
with:
title: ${{ env.PR_TITLE }}
body: ${{ env.PR_BODY }}

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

注意:有关在不同作业之间共享值的信息,请参阅此问题。

集合输出已折旧,更好的方法是现在:

echo "{name}={value}" >> $GITHUB_OUTPUT

来自 Github 文档的示例:

- name: Set color
id: random-color-generator
run: echo "SELECTED_COLOR=green" >> $GITHUB_OUTPUT
- name: Get color
run: echo "The selected color is ${{ steps.random-color-generator.outputs.SELECTED_COLOR }}"

最新更新