Search code examples
amazon-web-servicesaws-cloudformationamazon-ecsecs-taskdefinition

How to format CloudFormation Task Definition command


Hi I currently have a Task Definition resource as such:

  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

I would like to define ContainerDefinitions Command as

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

Any suggestions how to put it into yaml? I am getting Template Format Error if I put place the command directly in the template


Solution

  • The command should be a string according to cloudformation. In YAML sytax, Quotes are required when the string contains special or reserved characters.

    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 : :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, `

    you can read more about when to use the quotes in strings in the YAML documentation

    So In your case, you can escape the quotes like this.

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