是否可以在.gitlab-ci.yml中的多行命令中使用此处文档?

时间:2020-06-28 15:03:35

标签: gitlab gitlab-ci

是否可以在.gitlab-ci.yml中的多行命令中使用此处文档

我在扩展.gitlab-ci.yml作业中多行的命令中使用 here-document 时遇到困难。例如,我在下面创建了一个简短的测试作业,该作业使用 here-document 将多行字符串分配给环境变量PAYLOAD,然后将其用于curl请求中以将数据发布到url:< / p>

example:
  image: node:12-stretch-slim
  stage: mystage
  script:
    - >
      PAYLOAD=$(cat << 'JSON'
      '{
        "branch": "master",
        "commit_message": "some commit message",
        "actions": [
          {
            "action": "create",
            "file_path": "foo/bar",
            "content": "some content"
          }
        ]
      }'
      JSON
      )
    - >
      curl -X POST https://requestbin.io/1f84by61
      --header 'Content-Type: application/json; charset=utf-8'
      --data-binary "$PAYLOAD"
  when: manual
  only:
    - /^release-.*$/

以下脚本在gitlab.com CI服务器上失败并显示以下消息:

$ PAYLOAD=$(cat << 'JSON' '{ # collapsed multi-line command

[551](<private url>) /bin/bash: line 140: warning: here-document at line 140 delimited by end-of-file (wanted `JSON')

[552](<private url>) /bin/bash: line 139: warning: here-document at line 139 delimited by end-of-file (wanted `JSON')

[553](<private url>) cat: '{'$'\n'' "branch": "master",'$'\n'' "commit_message": "some commit message",'$'\n'' "actions": ['$'\n'' {'$'\n'' "action": "create",'$'\n'' "file_path": "foo/bar",'$'\n'' "content": "some content"'$'\n'' }'$'\n'' ]'$'\n''}': No such file or directory

[554](<private url>) cat: JSON: No such file or directory

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

阅读this

后已解决

使用|-保留命令内的换行符,并且不在命令字符串的末尾附加换行符。以前,我使用>,它用空格替换命令字符串中的换行符。

release:
  image: node:12-stretch-slim
  stage: release
  before_script:
    - apt-get update && apt-get install -y curl git jq
  script:
    - |-
      PAYLOAD=$(cat << JSON
      {
        "branch": "master",
        "commit_message": "some commit message",
        "actions": [
          {
            "action": "create",
            "file_path": "foo/bar",
            "content": "some content"
          }
        ]
      }
      JSON
      )
    - >
      curl -X POST https://requestbin.io/1f84by61
      --header 'Content-Type: application/json; charset=utf-8'
      --data-binary "$PAYLOAD"
  when: manual
  only:
    - /^release-.*$/