如何格式化 CloudFormation 任务定义命令

How to format CloudFormation Task Definition command

您好,我目前有一个任务定义资源:

  WebServerTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: !Ref TaskDefinitionName
      NetworkMode: awsvpc
      RequiresCompatibilities: 
        - FARGATE
      Cpu: !Ref TaskDefinitionCPU
      Memory: !Ref TaskDefinitionMemory
      ExecutionRoleArn: !Ref TaskDefinitionExecutionRole
      ContainerDefinitions: 
        - Name: !Ref ContainerName
          Image: !Ref ContainerImage
          Essential: true
          Cpu: 256
          EntryPoint: sh,-c
          Command: 
          PortMappings:
            - ContainerPort: !Ref ContainerPort

我想将ContainerDefinitionsCommand定义为

/bin/sh -c "echo '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p> </div></body></html>' >  /usr/local/apache2/htdocs/index.html && httpd-foreground"

有什么关于如何将其放入 yaml 的建议吗?如果我将命令直接放在模板中,我会收到模板格式错误

根据cloudformation,command应该是一个字符串。在 YAML 语法中,当字符串包含特殊或保留字符时需要引号。

Strings containing any of the following characters must be quoted. Although you can use double quotes, for these characters it is more convenient to use single quotes, which avoids having to escape any backslash : :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, `

您可以阅读有关何时在字符串中使用引号的更多信息in the YAML documentation

所以在你的情况下,你可以像这样转义引号。

WebServerTaskDefinition:
  Type: AWS::ECS::TaskDefinition
  Properties:
    Family: !Ref TaskDefinitionName
    NetworkMode: awsvpc
    RequiresCompatibilities:
      - FARGATE
    Cpu: !Ref TaskDefinitionCPU
    Memory: !Ref TaskDefinitionMemory
    ExecutionRoleArn: !Ref TaskDefinitionExecutionRole
    ContainerDefinitions:
      - Name: !Ref ContainerName
        Command:
          - "/bin/sh -c \"echo '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p> </div></body></html>' >  /usr/local/apache2/htdocs/index.html && httpd-foreground\""

参见https://yaml-multiline.info/

在这种情况下,最好使用 |-。例如:

example: |-\n
··Several lines of text,\n
··with some "quotes" of various 'types',\n
··and also a blank line:\n
··\n
··plus another line at the end.\n
··\n
··\n