Using IMDSv2 from within Docker container

After upgrading from IMDSv1 to IMDSv2, when I started a service that uses the AWS SDK inside a Docker container, I suddenly got a credential error. However, when I start the service on the host, it works fine as before.

We don’t need to define any AWS credentials, the AWS SDK, AWS CLI will automatically obtain the security credentials by requesting instance metadata.

I can get the metadata items by running the following command on the host, but no response is returned when the command is executed inside the container.

$ TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
&& curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/

By default, the PUT response hop limit is 1. So in a container environment, the IMDSv2 response will not be returned unless the hop limit is increased.

We can change the hop limit with the modify-instance-metadata-options command.

For example, set the --http-put-response-hop-limit parameter to 2 so that we can get the IMDSv2 response inside the container.

$ aws ec2 modify-instance-metadata-options --instance-id <instance_id> --region <region> --http-put-response-hop-limit 2

$ aws ec2 modify-instance-metadata-options --instance-id <instance_id> --region <region>
{
  "InstanceId": "<instance_id>",
  "InstanceMetadataOptions": {
    "State": "pending",
    "HttpTokens": "required",
    "HttpPutResponseHopLimit": 2,
    "HttpEndpoint": "enabled"
  }
}

Tags:

Updated: