格式化脚本和作业日志

您可以在 script 部分使用特殊语法:

script 中使用特殊字符

有时,script 命令必须用单引号或双引号括起来。 例如,包含冒号 (:) 的命令必须用单引号 (') 括起来。 YAML 解析器需要将文本解释为字符串而不是“键:值”对。

例如,此脚本使用冒号:

job:
  script:
    - curl --request POST --header 'Content-Type: application/json' "https://gitlab/api/v4/projects"

要被视为有效的 YAML,您必须将整个命令用单引号括起来。如果命令已经使用单引号,则应尽可能将它们更改为双引号 ("):

job:
  script:
    - 'curl --request POST --header "Content-Type: application/json" "https://gitlab/api/v4/projects"'

您可以使用 CI Lint 工具验证语法是否有效。

使用这些字符时也要小心:

  • {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, `.

忽略非 0 退出代码

当脚本命令返回非 0 的退出代码时,作业将失败并且不会执行进一步的命令。

将退出代码存储在变量中以避免这种行为:

job:
  script:
    - false || exit_code=$?
    - if [ $exit_code -ne 0 ]; then echo "Previous command failed"; fi;

为所有作业设置默认的 before_scriptafter_script

您可以将 before_scriptafter_scriptdefault 一起使用:

  • 使用 before_scriptdefault 来定义一个默认的命令数组,这些命令应该在所有作业中的 script 命令之前运行。
  • 默认使用 after_script 来定义应该在作业完成后运行的默认命令数组。

您可以通过在作业中定义不同的默认值来覆盖默认值。要忽略默认使用 before_script: []after_script: []

default:
  before_script:
    - echo "Execute this `before_script` in all jobs by default."
  after_script:
    - echo "Execute this `after_script` in all jobs by default."

job1:
  script:
    - echo "These script commands execute after the default `before_script`,"
    - echo "and before the default `after_script`."

job2:
  before_script:
    - echo "Execute this script instead of the default `before_script`."
  script:
    - echo "This script executes after the job's `before_script`,"
    - echo "but the job does not use the default `after_script`."
  after_script: []

拆分长命令

您可以使用 |(文字)和 >(折叠)YAML 多行块标量指示器 将长命令拆分为多行命令以提高可读性。

caution如果多个命令组合成一个命令字符串,则只报告最后一个命令的失败或成功。由于错误,早期命令的失败将被忽略。 要解决此问题,请将每个命令作为单独的 script 项运行,或者向每个命令字符串添加一个 exit 1 命令。

您可以使用 |(文字)YAML 多行块标量指示器在作业描述的 script 部分中的多行上编写命令。 每行都被视为一个单独的命令。 作业日志中仅重复第一条命令,但仍会执行其他命令:

job:
  script:
    - |
      echo "First command line."
      echo "Second command line."
      echo "Third command line."

上面的示例在作业日志中呈现为:

$ echo First command line # collapsed multiline command
First command line
Second command line.
Third command line.

>(折叠)YAML 多行块标量指示器将节之间的空行视为新命令的开始:

job:
  script:
    - >
      echo "First command line
      is split over two lines."

      echo "Second command line."

这与没有 >| 块标量指示符的多行命令类似:

job:
  script:
    - echo "First command line
      is split over two lines."

      echo "Second command line."

上面的两个示例在作业日志中呈现为:

$ echo First command line is split over two lines. # collapsed multiline command
First command line is split over two lines.
Second command line.

当您省略 >| 块标量指示符时,GitLab 连接非空行以形成命令。确保这些行在连接时可以运行。

下面的示例将小写字母音译为大写:

job:
  script:
    - |
      tr a-z A-Z << END_TEXT
        one two three
        four five six
      END_TEXT

结果是:

$ tr a-z A-Z << END_TEXT # collapsed multiline command
  ONE TWO THREE
  FOUR FIVE SIX

将彩色代码添加到脚本输出

可以使用 ANSI 转义码或通过运行输出 ANSI 转义码的命令或程序对脚本输出进行着色。

例如,使用带有彩色代码的 Bash

job:
  script:
    - echo -e "\e[31mThis text is red,\e[0m but this text isn't\e[31m however this text is red again."

您可以在 Shell 环境变量中定义彩色代码,甚至可以在自定义 CI/CD 变量中定义彩色代码,这使命令更易于阅读和重用。

例如,使用与上面相同的示例和在 before_script 中定义的环境变量:

job:
  before_script:
    - TXT_RED="\e[31m" && TXT_CLEAR="\e[0m"
  script:
    - echo -e "${TXT_RED}This text is red,${TXT_CLEAR} but this part isn't${TXT_RED} however this part is again."
    - echo "This text is not colored"

或者使用 PowerShell 彩色代码

job:
  before_script:
    - $esc="$([char]27)"; $TXT_RED="$esc[31m"; $TXT_CLEAR="$esc[0m"
  script:
    - Write-Host $TXT_RED"This text is red,"$TXT_CLEAR" but this text isn't"$TXT_RED" however this text is red again."
    - Write-Host "This text is not colored"

故障排查

Syntax is incorrect in scripts that use :

如果在脚本中使用冒号 (:),可能会输出:

  • Syntax is incorrect
  • script config should be a string or a nested array of strings up to 10 levels deep

例如,如果您使用 "PRIVATE-TOKEN: ${PRIVATE_TOKEN}" 作为 cURL 命令的一部分:

pages-job:
  stage: deploy
  script:
    - curl --header 'PRIVATE-TOKEN: ${PRIVATE_TOKEN}' "https://gitlab.example.com/api/v4/projects"

YAML 解析器认为 : 定义了一个 YAML 关键字,并输出 Syntax is wrong 错误。

要使用包含冒号的命令,您应该将整个命令用单引号括起来。您可能需要将现有的单引号 (') 更改为双引号 ("):

pages-job:
  stage: deploy
  script:
    - 'curl --header "PRIVATE-TOKEN: ${PRIVATE_TOKEN}" "https://gitlab.example.com/api/v4/projects"'

折叠 YAML 多行块标量不保留多行命令

如果您使用 -> 折叠 YAML 多行块标量来拆分长命令,额外的缩进会导致将这些行作为单独的命令进行处理。

例如:

script:
  - >
    RESULT=$(curl --silent
      --header
        "Authorization: Bearer $CI_JOB_TOKEN"
      "${CI_API_V4_URL}/job"
    )

这个命令失败了,因为缩进导致换行符被保留:

$ RESULT=$(curl --silent # collapsed multi-line command
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
/bin/bash: line 149: --header: command not found
/bin/bash: line 150: https://gitlab.example.com/api/v4/job: No such file or directory

通过以下任一方法解决此问题:

  • 删除额外的缩进:

    script:
      - >
        RESULT=$(curl --silent
        --header
        "Authorization: Bearer $CI_JOB_TOKEN"
        "${CI_API_V4_URL}/job"
        )
    
  • 修改脚本以便处理额外的换行符,例如使用 shell 行继续:

    script:
      - >
        RESULT=$(curl --silent \
          --header \
            "Authorization: Bearer $CI_JOB_TOKEN" \
          "${CI_API_V4_URL}/job")