【问题标题】:How to perform string manipulation while declaring env vars in GitHub Actions如何在 GitHub Actions 中声明环境变量时执行字符串操作
【发布时间】:2020-06-11 10:38:32
【问题描述】:

我有一个如下的 github 存储库

johndoe/hello-world

我正在尝试在 github 操作中设置以下环境变量

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}},类似于第一个有效?从here 看来可以。
  • ${{github.repository}} 包含用户名...我想在没有用户名的情况下获取它

标签: github environment-variables pipeline github-actions building-github-actions


【解决方案1】:

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

【讨论】:

  • set-env 自 2020 年 10 月起已弃用。建议的替换使用 $GITHUB_ENV 文件。
【解决方案2】:

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

  # Example of use 
  - name: Intalll 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

【讨论】:

    【解决方案3】:

    这样

    IMAGE_NAME_SERVER: "${{ REPOSITORY_NAME }}-server"
    

    【讨论】:

      【解决方案4】:

      截至本月的新产品,仍在“运行”中。

      https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/

      echo "action_state=yellow" >> $GITHUB_ENV

      我也发现uses:with:ref之类的东西不会进行${action_state}扩展,但是被塞满后会进行${{ env.action_state }}扩展。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-11
        • 2010-09-20
        • 2021-01-07
        • 2022-11-10
        • 2021-03-01
        • 2020-05-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多