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).
Enjoy!
#!/bin/bash
yum install -y aws-cli jq
REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
TAG_NAME="EcsClusterName"
CLUSTER_NAME=""
while [ "$CLUSTER_NAME" == "" ]
do
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)
done
echo ECS_CLUSTER="$CLUSTER_NAME" >> /etc/ecs/ecs.config