YAML无效 - 可能是引号问题

3

我从Gitlab CI/CD管道中获取错误信息:yaml invalid。问题是由.gitlab-ci.yml脚本的第五行引起的:

   - 'ssh deployer@gitadam.ga \'rm /var/www/html/hosts/production/current/temp__*\''

脚本的部分。
script:
    - 'pwd'
    - 'whoami'
    - 'ls temp__*'
    - 'ssh deployer@gitadam.ga \'rm /var/www/html/hosts/production/current/temp__*\''
    - 'if ls temp__* 1> /dev/null 2>&1; then for file in temp__*; do scp $file deployer@gitadam.ga:/var/www/html/hosts/production/current/; done; fi'

如何修复代码中的错误?

3个回答

7
你可以直接保留开始和结束的单引号,不需要使用强制删除它们。这样做可能会导致其他错误(虽然在这种情况下不会),而且在你的情况下不足以获得想要的结果。
真正的问题在于,你试图以错误的方式转义单引号。在单引号标量中,唯一需要转义的字符是单引号。所以不能使用反斜杠进行转义,因为在单引号标量内部也需要对反斜杠进行转义。
要在单引号标量中转义单引号,需要将其重复两次。
YAML规范中,措辞略有不同,但效果相同:
引号括起来的单引号风格由“'”指示符指定。因此,在单引号标量中,这些字符需要重复。这是在单引号标量中执行的唯一转义形式。特别地,“\”和“"”字符可以自由使用。

所以要更改第5行,只需将两个反斜杠更改为单引号:

script:
    - 'pwd'
    - 'whoami'
    - 'ls temp__*'
    - 'ssh deployer@gitadam.ga ''rm /var/www/html/hosts/production/current/temp__*'''
    - 'if ls temp__* 1> /dev/null 2>&1; then for file in temp__*; do scp $file deployer@gitadam.ga:/var/www/html/hosts/production/current/; done; fi'

在YAML的双引号标量中,您可以使用反斜杠转义双引号,也可以转义各种特殊字符或使用YAML功能。但是单引号无法以这种方式进行转义。如果使用双引号,第五行需要删除反斜杠:

    - "ssh deployer@gitadam.ga 'rm /var/www/html/hosts/production/current/temp__*'"

保留引号有多个原因。如果你的标量以特殊字符(对于YAML而言)开头,你就需要使用引号。仅仅以字母(A-Za-z)开头是不够的:如果该标量恰巧包含特殊序列,如注释起始序列(空格+八角符号)或值指示器(冒号+空格)序列,则必须使用引号。
使用单引号比不使用更安全,你只需要知道如何转义它们即可。它们有时可能是多余的,但是在定义YAML中的标量字符串方面,它们是最简单的方法(考虑到需要考虑的异常数量)。

¹如果您删除前导和尾随单引号,则需要像第5行一样删除反斜杠。

²这里的“it”指的是单引号,当然不是整个标量。


2
在此发帖之前,你应该尝试自己一次不使用引号。但是,看起来是因为那个原因。
script:
  - pwd
  - whoami
  - ls temp__*
  - ssh deployer@gitadam.ga 'rm /var/www/html/hosts/production/current/temp__*'
  - if ls temp__* 1> /dev/null 2>&1; then for file in temp__*; do scp $file deployer@gitadam.ga:/var/www/html/hosts/production/current/; done; fi

GitLab还内置了一个用于CI语法的linter。

enter image description here


1

在GitLab CI中格式化ssh命令的另一个选项可能是:

job:
  script:
    - >
      ssh -o StrictHostKeyChecking=no user@host bash -s << 'EOF'
        echo "test"
        echo "test2"
      EOF

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