首页 > 解决方案 > 如何格式化 CloudFormation 任务定义命令

问题描述

嗨,我目前有一个任务定义资源,例如:

  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

我想定义ContainerDefinitions 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"

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

标签: amazon-web-servicesamazon-cloudformationamazon-ecsecs-taskdefinition

解决方案


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

必须引用包含以下任何字符的字符串。虽然您可以使用双引号,但对于这些字符使用单引号更方便,这样可以避免转义任何反斜杠::, {, }, [, ], ,, &, *, #, ?, |, - , <, >, =, !, %, @, `

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

因此,在您的情况下,您可以像这样转义引号。

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\""

推荐阅读