带有 curl 的脚本之前的 Gitlab CI 变量引发 YAML 语法错误

Gitlab CI variable before script with curl raises YAML syntax error

我正在定义一个变量 JWT,我将在其中存储一个令牌,稍后我将在代码中使用它。 我将通过 curl 调用在 before_script 步骤中获取它。

问题是,当我尝试 运行 管道时,它失败并显示错误:

Found errors in your .gitlab-ci.yml: Included file .gitlab-ci.yml does not have valid YAML syntax!

为了正确插入 USERPASS 环境变量,我已经阅读了这个

这是我的 .gitlab-ci.yml 文件:


build-dist:
  environment:
    name: develop
  variables:
    JWT: ""
  stage: build
  image: node:16-alpine
  cache:
    key:
      files:
        - yarn.lock
    paths:
      - node_modules
      - .yarn
  before_script:
    - if [ -z "$USER" ] || [ -z "$PASS" ]; then exit 1; fi
    - apk add curl 
    - JWT=$(curl -s -X POST -H "Content-Type: application/json" -d '{"username": "'"$USER"'","password": "'"$PASS"'"}' "https://example.com/token")

  script: 
    - yarn install --pure-lockfile --cache-folder .yarn
    - yarn build

我应该如何更正 .gitlab-ci.yml 中的后续行以使其正常工作?

- JWT=$(curl -s -X POST -H "Content-Type: application/json" -d '{"username": "'"$USER"'","password": "'"$PASS"'"}' "https://example.com/token")

首先,关于此类 GitLab CI 问题的实用提示:

  • 假设您在 https://gitlab.com/user/project
  • 上有一个 GitLab 存储库
  • 您可以浏览页面https://gitlab.com/user/project/-/ci/lint
  • 然后粘贴有问题的 .gitlab-ci.yml 文件的内容,然后单击“验证”以获得更多反馈(通常是错误行号等)

关于 YAML 代码段,问题的症结在于您在问题中提到的 - JWT=$(…) 行,更准确地说:

  • 从 YAML 的角度来看,字符串 JWT=… 没有被显式引用,
  • 并且由于此文本包含 :
  • 然后 YAML 解析器将其视为地图,即,就好像您已经编写了:
    - username: "NAME"
      other_key: "val"
    

为了解决这个问题,看来您只需要用 '" 来“引用”这个序列项,然后写下 - "JWT=…" 形式的一行,然后在里面相应地转义引号……但我宁愿建议(避免丑陋的转义!)依靠所谓的 block style of YAML → 这导致:​​

- |
  JWT=$(curl -s -X POST -H "Content-Type: application/json" -d '{"username": "'"$USER"'","password": "'"$PASS"'"}' "https://example.com/token")