Issue
I'd like to use IMDSv2 inside a container running on an EC2 instance.
I want to use the tokens because they are required in my metadata options:
metadata_options {
http_tokens = "required"
http_endpoint = "enabled"
}
Calling the API from the EC2 instance returns my token as expected.
curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"
However, if I try to call it from a docker container:
docker run -it curlimages/curl sh
/ $ curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"
curl: (56) Recv failure: Connection reset by peer
I just have a timeout.
According to this answer, it should work out of the box, but it's not. If I add a --network=host
flag, it works, but that's not a solution for me.
Thanks
Solution
I order to access IMDSv2 metadata from a docker container, you must increase the hop limit for IMDSv2 in the instance metadata configuration. From the aws docs:
In a container environment, if the hop limit is 1, the IMDSv2 response does not return because going to the container is considered an additional network hop. To avoid the process of falling back to IMDSv1 and the resultant delay, in a container environment we recommend that you set the hop limit to 2
To change the hop limit, you can use modify-instance-metadata-options
in awscli:
aws ec2 modify-instance-metadata-options \
--instance-id <instance_id> \
--http-put-response-hop-limit 2 \
--http-endpoint enabled
Answered By - jordanm Answer Checked By - Dawn Plyler (WPSolving Volunteer)