在 EC2 或 ECS 上使用带有 docker 内令牌的 IMDS (v2)

Using IMDS (v2) with token inside docker on EC2 or ECS

我想在 EC2 实例上的容器 运行 中使用 IMDSv2。

我想使用令牌,因为它们在我的元数据选项中是必需的:

metadata_options {
  http_tokens   = "required"
  http_endpoint = "enabled"
}

按预期从 EC2 实例 returns 我的令牌调用 API。

curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"

但是,如果我尝试从 docker 容器中调用它:

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

我只是有一个超时。

根据 this answer,它应该开箱即用,但事实并非如此。如果我添加一个 --network=host 标志,它会起作用,但这不是我的解决方案。

谢谢

我为了从 docker 容器访问 IMDSv2 元数据,您必须在实例元数据配置中增加 IMDSv2 的跳数限制。来自 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

要更改跃点限制,您可以在 awscli 中使用 modify-instance-metadata-options

aws ec2 modify-instance-metadata-options \
    --instance-id <instance_id> \
    --http-put-response-hop-limit 2 \
    --http-endpoint enabled