在 GitHub Actions 中,我可以返回一个值以供以后用作条件吗?

Mic*_*tum 8 github-actions

我正在将 GitHub Actions 设置为我的一个项目的 CI,整个构建过程基本上是一个 PowerShell 脚本,由环境变量驱动。

这既是为了最大限度地减少供应商锁定,并确保我可以使用几乎相同的过程在本地运行构建。

现在,我的构建脚本确定了一些内容并将其放入环境变量中 - 具体来说,我有一个MH_IS_PROD_BUILDTrue 或 False的变量,并确定我推送到哪个 nuget 包存储库。

但是,当运行 shell 的步骤完成时,环境变量将不复存在,因为进一步的步骤似乎是在新环境中运行的。

想做的是这样的事情(缩写):

  steps:
    - name: Run build script
      id: pwshbuild
      shell: pwsh
      run: |
        cd scripts
        ./build.ps1
        # The above sets $Env:MH_IS_PROD_BUILD to either True or False
    - name: Push Publish to GPR (Dev Package)
      if: steps.pwshbuild.outputs.MH_IS_PROD_BUILD == 'False'
      shell: pwsh
      run: |
        # omitted: determine $nupkgPath
        nuget push $nupkgPath -Source "GPR" -SkipDuplicate
    - name: Push Publish to Nuget.org (Release Package)
      if: steps.pwshbuild.outputs.MH_IS_PROD_BUILD == 'True' 
      shell: pwsh
      run: |
        # omitted: determine $nupkgPath
        nuget push $nupkgPath -Source "NugetOrg" -SkipDuplicate
Run Code Online (Sandbox Code Playgroud)

输出似乎是我需要的,但这似乎需要创建自定义操作?

以上当然不起作用(因此询问)。所以我想知道,最好的方法是什么?

  • 我可以从 PowerShell 设置步骤的输出吗?(首选)
  • 我是否必须创建一个自定义操作来封装我对 build.ps1 的调用,以便我可以通过输出返回内容?

pet*_*ans 10

我认为您可以通过将它们回显到控制台来设置 Powershell 的输出。Powershell 有一个别名映射 echo 到Write-Output.

jobs:
  windows-test:
    runs-on: windows-latest
    steps:
      - uses: actions/checkout@v1
      - name: Set outputs
        id: vars
        shell: pwsh
        run: echo "::set-output name=production::true"
      - name: Check outputs
        shell: pwsh
        run: echo ${{ steps.vars.outputs.production }}
Run Code Online (Sandbox Code Playgroud)

参考:https : //help.github.com/en/github/automating-your-workflow-with-github-actions/development-tools-for-github-actions#set-an-output-parameter-set-output


Sam*_*ira 5

除了peterevans回答之外,您仍然可以使用环境变量作为条件,只要它们是通过::set-env "command"设置的

例子:

- run:   |
         if [ -f FileMightNotExists.txt ]; then
            echo ::set-env name=HAVE_FILE::true
         fi
  shell: bash

- run: echo "I have file!"
  if:  env.HAVE_FILE == 'true'
Run Code Online (Sandbox Code Playgroud)

如前所述,已经有::set-output,所以这主要是品味问题。

使::set-env更易于使用的原因(在我看来)是您不需要设置id步骤(更少输入),引用 vars 更短(再次更少输入),您添加的所有变量都将列出每个步骤(折叠在Run块内,在尝试查找工作流中的错误时会很有用),而且……它最终只是常规变量,可能更容易使用,取决于 shell。

  • `set-env` 已被声明为已弃用:https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/ (2认同)