在Yaml中转义包含引号和撇号的cURL命令

时间:2017-04-05 06:59:10

标签: curl escaping yaml gitlab-ci

我有这个cURL命令:

curl -X POST --data-urlencode 'payload={"text": "A new version has been deployed to production."}' https://hooks.slack.com/services/XXXXXXX/XXXXXXXXX/XXXXXXXXXXXXX

我需要在具有Yaml支持的GitLab CI文件中使用它。 Yaml解析器不接受它。通常我会用引号括起来,但我已经在命令中使用了引号和撇号。

这就是命令现在的样子。

如何正确地逃避序列?

deploy:
  stage: deploy
  script:
    - "curl -X POST --data-urlencode 'payload={"text": "A new version has been deployed to production."}' https://hooks.slack.com/services/XXXXXXX/XXXXXXXXX/XXXXXXXXXXXXX"

1 个答案:

答案 0 :(得分:12)

最简单的方法是使用块标量:

deploy:
  stage: deploy
  script: |-
    curl -X POST --data-urlencode 'payload={"text": "A new version has been deployed to production."}' https://hooks.slack.com/services/XXXXXXX/XXXXXXXXX/XXXXXXXXXXXXX

|启动一个文字块标量,-告诉YAML丢弃尾随换行符(否则它将成为标量的一部分)。为了便于阅读,您可以使用折叠块标量(换行符将转换为空格):

deploy:
  stage: deploy
  script: >-
    curl -X POST --data-urlencode 'payload={"text":
    "A new version has been deployed to production."}'
    https://hooks.slack.com/services/XXXXXXX/XXXXXXXXX/XXXXXXXXXXXXX

最后,也可以使用双引号,只要你在标量内转义双引号(换行符也会折叠成空格):

deploy:
  stage: deploy
  script: 
    "curl -X POST --data-urlencode 'payload={\"text\":
     \"A new version has been deployed to production.\"}' 
     https://hooks.slack.com/services/XXXXXXX/XXXXXXXXX/XXXXXXXXXXXXX"