如何在GitHub Actions中声明环境变量时执行字符串操作

21

我有一个如下所示的GitHub仓库

johndoe/hello-world

我正在尝试在GitHub Actions中设置以下环境变量

env:
  DOCKER_HUB_USERID: ${{ github.actor }}
  REPOSITORY_NAME: ${GITHUB_REPOSITORY#*\/}
  IMAGE_NAME_CLIENT: "$REPOSITORY_NAME-client"
  IMAGE_NAME_SERVER: "$REPOSITORY_NAME-server"

我对这些变量的预期结果是:

johndoe
hello-world
hello-world-client
hello-world-server

但是我正在得到某些东西。

johndoe
${REPOSITORY_NAME#*\/}
$REPOSITORY_NAME-client
$REPOSITORY_NAME-server
看起来在声明 env 变量时,表达式没有被评估。
我该如何实现预期行为?

为什么第二个不用${{github.repository}},和第一个一样可以工作呢?从这里看起来应该是可以的。 - Wayne
${{github.repository}} 包括用户名... 我想要在没有用户名的情况下获取它。 - Rakib
4个回答

22
在一个run步骤之外,不可能进行Shell参数扩展。
env:
  REPOSITORY_NAME: ${GITHUB_REPOSITORY#*\/}
创建一个额外的步骤来计算这个值到一个新变量中,并将其附加到文件$GITHUB_ENV中。
      - name: Set env
        run: echo "REPOSITORY_NAME=${GITHUB_REPOSITORY#*\/}" >> $GITHUB_ENV
      - name: Test
        run: echo $REPOSITORY_NAME

或者创建一个步骤输出。

      - name: Set outputs
        id: vars
        run: echo ::set-output name=repo_name::${GITHUB_REPOSITORY#*\/}
      - name: Test set output
        run: echo ${{ steps.vars.outputs.repo_name }}

一旦计算出环境变量 REPOSITORY_NAME,或步骤输出 steps.vars.outputs.repo_name 存在,它们可以用来设置其他变量,如下所示。

env:
  IMAGE_NAME_CLIENT: ${{ env.REPOSITORY_NAME }}-server
  IMAGE_NAME_SERVER: ${{ steps.vars.outputs.repo_name }}-server

3
自2020年10月以来,set-env 已被弃用。建议使用 $GITHUB_ENV 文件作为替代方案。 - Benoit Blanchon

8

Github出于安全考虑已更改设置环境变量的方式,现在必须使用以下方法。

steps:
  - name: Set the environment variable
    run: echo REPOSITORY_NAME=${GITHUB_REPOSITORY#*\/} >> $GITHUB_ENV

然后像这样使用它

  - name: Use the value
    run: echo $REPOSITORY_NAME # This will output repository name

在env中使用的示例

  - name: Install dependencies And Build Yarn and npm
    uses: fabiel-leon/npm-build@master
    env:
      REPO: ${{ env.REPOSITORY_NAME }}

  - name: Build and push Docker images
    uses: docker/build-push-action@v1
    with:
      tags: ${{ env.REPOSITORY_NAME }}

https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable


4

3
像这样
IMAGE_NAME_SERVER: "${{ REPOSITORY_NAME }}-server"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接