Accessing EC2 metadata service from CodeBuild instance

I'm running a docker container from within AWS CodeBuild inside my VPC. On the host, I have no problem running aws sts get-caller-identity with no credentials. E.g.:

aws sts get-caller-identity
{
    "UserId": "[redacted]",
    "Account": "[redacted]",
    "Arn": "arn:aws:sts::[redacted]:assumed-role/[redacted]"
}

Inside the docker container however, I get an error trying to get my identity:

% aws sts get-caller-identity
Couldn't reach EC2 metadata service.

Unable to locate credentials. You can configure credentials by running "aws configure".

I assume this is because I can't reach the EC2 metadata service to obtain the role keys, but I thought that should "just work" since the container should have access to the same network as the host.

So I backed out and took another look at the host - it looks like I can't access the metadata service on http://169.254.169.254:

# curl -kv http://169.254.169.254/latest/meta-data/public-hostname
*   Trying 169.254.169.254:80...
* TCP_NODELAY set
* Immediate connect fail for 169.254.169.254: Invalid argument
* Closing connection 0
curl: (7) Couldn't connect to server

How is aws sts working on the host? I thought the AWS CLI needed access to that metadata service if credentials weren't supplied. How can I get it working inside the container (I don't want to pass long lived tokens around in environment variables)?

(edited with additional detail found from exploring directly on SessionManager in the CodeBuild instance)


Best I've found for this so far...

Thanks for the comment from @Tim, CodeBuild runs on ECS. When it does that, it pulls credentials from container credentials. Those are apparently pulled from a different IP address, which can be accessed via

169.254.170.2$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI

You can extract the role credentials from that call and then pass them into the Docker container.