Back to list of posts

Using EC2 Tags to Dynamically Join ECS Cluster

On one of my projects, we have a shared launch configuration that is then used for multiple auto-scaling groups. Each ASG is then attached to its own ECS cluster. So, we wanted to use EC2 tags to specify the cluster to join. Sound good, right? Well…

In the RunInstance spec (under TagSpecification.N), we see:

The tags to apply to the resources during launch. … The specified tags are applied to all instances or volumes that are created during launch. (emphasis added)

But, user data also runs “during launch.” We found that, at times, the tags weren’t applied to the instance when the user data ran.

So, here’s a script that simply keeps trying until the tags are available. It uses the EcsClusterName tag from the EC2 instance and uses that to configure the ECS agent (more info here).


yum install -y aws-cli jq

REGION=$(curl -s | jq -r .region)
INSTANCE_ID=$(curl -s


while [ "$CLUSTER_NAME" == "" ]
  sleep 1
  CLUSTER_NAME=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=$TAG_NAME" --region=$REGION --output=text | cut -f5)

echo ECS_CLUSTER="$CLUSTER_NAME" >> /etc/ecs/ecs.config