使用带反斜杠的 sed 命令时出现 AWS CloudFormation 模板验证错误

AWS CloudFormation template validation error when using sed command with backslash

我正在尝试将与部署相关的变量添加到 AWS lambda 无服务器-output.yaml 文件,方法是通过 AWS CloudFormation 模板向文件添加几行。

我有以下 sed 命令:

sed -ie '/^    Properties:/a\      Tags:' ./serverless-output.yaml

当我 运行 在亚马逊 linux 的命令行中时,它会按预期进行并添加标签:在属性下正确缩进的行:行

EC2StartStop:
  Properties:
    Tags:

当我将行放入 cloudformation 模板时,出现格式错误:

"sed -ie '/^    Properties:/a\      Tags:' ./serverless-output.yaml",

Error
Template validation error: Template format error: JSON not well-formed.
(line 200, column 36)

要消除错误,看来我必须删除“/a”后的反斜杠:

"sed -ie '/^    Properties:/a    Tags:' ./serverless-output.yaml"

但是 Tags: 行没有缩进,导致 .yaml 文件中出现语法错误:

  EC2StartStop:
    Properties:
Tags:

sed 命令可以很好地识别我需要插入行的位置,但是当通过 cloudformation 使用 运行ning 命令时,如何在插入的行上获得正确的缩进?

不知道 cloudformation template 规则,但通常双引号字符串允许 \ 用于特殊序列,允许 non-printable 个字符及其 oct/hex表示等。例如:\" 表示引号内的双引号字符。因此,要表示 \ 需要 \

"sed -ie '/^    Properties:/a\      Tags:' ./serverless-output.yaml",