Inject configuration files in an Elastic Container Service (ECS) task definition

Nathan Peck profile picture
Nathan Peck
Senior Developer Advocate at AWS

The following snippet shows how to do runtime file generation and injection in an ECS task definition.

It launches an NGINX reverse proxy server, directly from Amazon Elastic Container Registry Public. This default container does not do anything except show a simple "welcome to NGINX" message. However, we can use a command to generate the custom NGINX configuration at runtime, prior to launching the container. Because this command runs inside the container as it launches we can even use custom environment variables from the task definition.


You will find that the richer feature set of YAML makes the embedded config file in the CloudFormation YAML much easier to read than the single line string inside of the raw JSON task definition.

If you intend to create more advanced task definitions it is highly recommended to use AWS CloudFormation. If you do not wish to use CloudFormation then consider still writing your task definitions in YAML, and use yq to convert the YAML to JSON for the ECS API.

  • AWS CloudFormation
  • Raw JSON
File: task-definition.ymlLanguage: yml
AWSTemplateFormatVersion: '2010-09-09'
Description: An example task definition which self generates and injects
             a config file for the running application.


    Type: AWS::ECS::TaskDefinition
      Family: nginx-ingress
      Cpu: 256
      Memory: 128
        - Name: nginx
            - '/bin/sh'
            - '-c'
            - Name: MY_URL_ENV_VARIABLE
            - >
              echo "
                events {
                  worker_connections  1024;
                  upstream ingress
                    server $MY_URL_ENV_VARIABLE;
                  server {
                    listen 8080;
                    location /
                      proxy_pass http://ingress;
                      proxy_set_header Host \$host;
                      proxy_pass_request_headers on;
              " > /etc/nginx/nginx.conf &&
              exec nginx -g 'daemon off;'

Deploy the CloudFormation template above by using the AWS CloudFormation web console. Alternatively you can deploy from the command line with:

Language: sh
aws cloudformation deploy \
   --stack-name sample-task-definition \
   --template-file task-definition.yml

See Also