Search code examples
amazon-web-servicesamazon-ec2aws-cliamazon-ecs

How to get the container-instance-id of the local ec2 instance


I run the following shell command to drain my ECS instance before rebooting it:

INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
aws ecs update-container-instances-state \
  --region eu-central-1 \
  --cluster mycluster \
  --status DRAINING \
  --container-instances $INSTANCE_ID

It gives me the following error:

An error occurred (InvalidParameterException) when calling the UpdateContainerInstancesState operation: instanceId shorter than 36.

Apparently this is because it wants the ECS containerInstanceId which is different from the ec2InstanceId. What is the best way to find out the containerInstanceId of the local machine?

The way I figured out so far is

  1. use aws ecs list-container-instances to get all the container instance IDs in the cluster
  2. use aws ecs describe-container-instances to get the corresponding EC2 instance IDs
  3. use instance metadata (http://169.254.169.254/latest/meta-data/instance-id) to find out the local EC2 instance ID
  4. Use jq combined with grep or some other tool to filter

This seems a little complicated. Is there a simpler way?


Solution

  • If you're running a script on the instance, you can find the container instance ID from the ECS agent's introspection API.

    If you're running a script from within an ECS task, you can use the container metadata file.