Add environment variable to ECS host

4.6k views Asked by At

I am trying to set an environment variable in the EC2 instance hosting ECS containers. The environment variable should be readable by the docker client on the EC2 instance at run time. I know it's possible to add userData like so:

#!/bin/sh
echo export env_var=1 >> /etc/environment

But for some reason this env_var is not being picked up by the docker client when instantiating ECS tasks.

Any idea how I might go about doing this? Thanks in advance.

2

There are 2 answers

1
byunghyun park On

Are you simply adding environment variables? Then try the following

  1. Add variable in Dockerfile

    ARG DEV

    ENV DEV=${DEV}

  2. Add variable when build docker image

    docker build . -t projectname --build-arg DEV=False

1
John Veldboom On

You can define environment variables from within the task definition that will get passed into your container using Docker's --env option. Advanced Container Definition Parameters (scroll down to "environment")

"environment" : [
    { "name" : "string", "value" : "string" },
    { "name" : "string", "value" : "string" }
]

Here's a quick sample of where how it looks on a full task definition:

{
    "family": "example-task",
    "containerDefinitions": [
        {
            "name": "sample-app",
            "image": "123456789012.dkr.ecr.us-west-2.amazonaws.com/aws-nodejs-sample:v1",
            "memory": 200,
            "cpu": 10,
            "essential": true,
            "environment": [
                {
                    "name": "ENVIRONMENT",
                    "value": "production"
                },
                {
                    "name": "API_HOST",
                    "value": "https://example.com"
                }
            ],
        }
    ]
}