Create new Elastic Container Service (ECS) task definition revision

Nathan Peck profile picture
Nathan Peck
Senior Developer Advocate at AWS

About

This script demonstrates the use of a Bash here document to embed a task definition template in a deploy script. You can interpolate variable values from the bash script into the task definition template, and then pass the entire JSON structure to the aws ecs create-task-definition CLI command using the --cli-input-json flag.

Example deploy script

File: script.shLanguage: sh
IMAGE_URL="httpd:2.4"
CPU=256
MEMORY=512

export TASK_DEFINITION=$(cat << EOF
{
   "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\""
         ],
         "entryPoint": [
            "sh",
            "-c"
         ],
         "essential": true,
         "image": "$IMAGE_URL",
         "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
               "awslogs-group" : "/ecs/fargate-task-definition",
               "awslogs-region": "us-east-1",
               "awslogs-stream-prefix": "ecs"
            }
         },
         "name": "sample-fargate-app",
         "portMappings": [
            {
               "containerPort": 80,
               "hostPort": 80,
               "protocol": "tcp"
            }
         ]
      }
   ],
   "cpu": "$CPU",
   "executionRoleArn": "arn:aws:iam::012345678910:role/ecsTaskExecutionRole",
   "family": "fargate-task-definition",
   "memory": "$MEMORY",
   "networkMode": "awsvpc",
   "requiresCompatibilities": [
       "FARGATE"
    ]
}
EOF
)

aws ecs register-task-definition --cli-input-json "$TASK_DEFINITION"

Installation

Download the script and use chmod on the command line to make it executable:

Language: sh
chmod +x script.sh

You can then run the script on the command line with

Language: sh
./script.sh

Next steps

  • Customize the embedded task definition with your own application's details
  • Add some docker commands to the top of the script to build and push a new version of your container image
  • Add the script to your Git repository and use a CI/CD solution to automatically run the deploy script whenever you merge code into your repository.