GitHub Actions:在特定操作系统上运行步骤

115

我正在使用GitHub Actions在多个操作系统上运行工作流。

但是,有一个特定的步骤只需在Ubuntu上运行:

runs-on: ${{ matrix.os }}
strategy:
    matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
steps:
    - name: Setup Ubuntu
      run : export DISPLAY="127.0.0.1:10.0"
      if: # --> What should be here? <--

我该如何仅在特定的操作系统上运行步骤?


一种选择是将作业分开,这样您就可以清楚地知道在任何操作系统中采取了哪些步骤。 - Morteza
2个回答

192

您可以使用以下任一条件:if: matrix.os == 'NAME_FROM_MATRIX'if: runner.os == 'OS_TYPE'

用于检查矩阵上下文:

if: matrix.os == 'ubuntu-latest'

if: matrix.os == 'windows-latest'

if: matrix.os == 'macos-latest'

用于检查执行器上下文:

if: runner.os == 'Linux'

if: runner.os == 'Windows'

if: runner.os == 'macOS'

相关文档:runner context

更新

GitHub 现在提供了 RUNNER_OS 变量,它简化了在单个步骤中的检查过程:

- name:  Install
  run:   |
         if [ "$RUNNER_OS" == "Linux" ]; then
              apt install important_linux_software
         elif [ "$RUNNER_OS" == "Windows" ]; then
              choco install important_windows_software
         else
              echo "$RUNNER_OS not supported"
              exit 1
         fi
  shell: bash

这可能是更复杂步骤的更好方法,其中当前操作系统只是众多变量之一。

使用 if: matrix.os == ubuntu-latest 时,我遇到了以下错误: 无法识别的命名值:'ubuntu-latest'。该值位于表达式中的第14个位置:matrix.os == ubuntu-latest。但是,if: runner.os == 'Linux' 对我有效。谢谢! - yahavi
5
如果使用matrix.os == 'ubuntu-latest'应该可以 - 你需要在那里加上引号。 - Edward Thomson
14
请注意,这里必须使用单引号,双引号会导致语法错误。请留意不改变原本的意思,使翻译更加通俗易懂。 - Markus Amalthea Magnuson
4
在Windows环境下,if语句中缺少'('。 - decades
12
@decades,你在步骤中没有添加shell: bash。如果没有这行代码,工作流程将使用默认的 shell(在 Windows 上是 PowerShell),你会得到你提供的错误信息。这里的shell: bash并不是为了修饰,而是为了确保该步骤在所有平台上都能正确运行。请参考https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#using-a-specific-shell。 - Samira
显示剩余6条评论

5

通过Google搜索来到这里。

如果你在使用矩阵构建时遇到了行尾问题,并且想要在Linux和macOS运行器上避免不必要的设置Git配置,可以使用以下方法:

  - if: runner.os == 'Windows'
    run: |
      git config --global core.autocrlf false
      git config --global core.eol lf

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