Escape-Characters

如何以正確的方式在 YAML 中轉義?

  • April 27, 2016

在 CentOS 7 上,我使用 cloud-init 使用需要 YAML 格式的 DigitalOcean API 來分離一個液滴。

我得到了大部分工作正常,但在逃避下面“runcmd”執行的命令時遇到了困難:

#!/bin/sh

set -e     # Stop on first error

curl  -X POST https://api.digitalocean.com/v2/droplets \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer '$api_key'' \
-d '{
"name":"'$droplet_name'",
"region":"'$region'",
"size":"'$size'",
"image":"'$image'", 
"ssh_keys":'$root_ssh_pub_key',
"backups":false,
"ipv6":false,
"private_networking":false,
"user_data":"
   #cloud-config

   users:
   - name: SomeUser
     groups: wheel
     shell: /bin/bash
     ssh-authorized-keys:
             - ssh-dss AAAABBBBCCCCDDDDD...

   runcmd:
   - sed -i -e '$aAllowUsers SomeUser' /etc/ssh/sshd_config
   - sed -i -e '/PermitRootLogin/s/^.*$/PermitRootLogin no/' /etc/ssh/sshd_config
   - service sshd restart
"}'

我收到的錯誤是:

curl: (6) Could not resolve host: no
curl: (3) [globbing] unmatched close brace/bracket in column 63

您將單引號用於-d命令行選項,既用於指定由分隔的字元串$variable,也用於引用第二個sed命令的參數。

因為$aAllowUsers SomeUser這可能是你想要的,但這/PermitRootLogin/s/^.*$/PermitRootLogin no/可能不是你想要/bin/sh擴展的。將反斜杠放在那裡應該有幫助:

  - sed -i -e \'/PermitRootLogin/s/^.*$/PermitRootLogin no/\' /etc/ssh/sshd_config

YAML 不應該對在標量值中間有單引號的列表項有任何問題。

使用 heredoc 進行此類輸入。appliaction/json而且您需要轉義換行符和引號,因為它們在您的構造中是不允許的。

user_data=$(awk -v 'ORS=\\n' 1 <<'HERE' | sed 's/"/\\"/g'
#cloud-config

users:
- name: SomeUser
 groups: wheel
 shell: /bin/bash
 ssh-authorized-keys:
 - ssh-dss AAAABBBBCCCCDDDDD...

runcmd:
- sed -i -e '$aAllowUsers SomeUser' /etc/ssh/sshd_config
- sed -i -e '/PermitRootLogin/s/^.*$/PermitRootLogin no/' /etc/ssh/sshd_config
- service sshd restart
HERE
)

curl -X POST https://api.digitalocean.com/v2/droplets \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $api_key" \
-d - <<HERE 
{
 "name": "$droplet_name",
 "region": "$region",
 "size": "$size",
 "image": "$image", 
 "ssh_keys": "$root_ssh_pub_key",
 "backups": false,
 "ipv6": false,
 "private_networking": false,
 "user_data": "$user_data"
}
HERE

引用自:https://unix.stackexchange.com/questions/178695