Search code examples
amazon-ecsamazon-ecr

Discover AWS ECS cluster association from running container (self managed cluster)


I'm working with ECS with self managed EC2 based clusters. We have 1 cluster for each env, dev/stage/prod

I'm struggling to have my containers in ECS be aware of what cluster / environment they start in so that on task start up time they can properly configure themselves without having to bake the env specific config into the images.

It would be really easy if there was some command to run inside the container that could return the cluster name. It seems like that should be easy. I can think of a few sub optimal ways to do this. get the container/host IP and look up the instance. Try to grab /etc/ecs/ecs.config from the host instance etc...

It seems like there should be a better way. my google skills are failing... thx!


Solution

  • The ECS Task Metadata endpoint, available at ${ECS_CONTAINER_METADATA_URI_V4}/task within any ECS task, will return the cluster name, among other things.

    Alternatively, if you were using an IaC tool such as Terraform or CloudFormation to build your ECS tasks, it would be trivial to inject the cluster name as an environment variable in the tasks.