iTranslated by AI
Using AWS CLI in Docker Containers on AWS CloudShell
AWS CloudShell now supports Docker.
I thought, "Now I can test containers on CloudShell too—all set!" but then...
# Run in a container on CloudShell
~ $ docker run -it public.ecr.aws/aws-cli/aws-cli s3 ls
Unable to locate credentials. You can configure credentials by running "aws login".
I don't really get it, but it works, so we're good!
Just kidding. I'll explain later.
eval $(curl -s -H "X-aws-ec2-metadata-token: $AWS_CONTAINER_AUTHORIZATION_TOKEN" $AWS_CONTAINER_CREDENTIALS_FULL_URI \
| jq -r "[\"export AWS_ACCESS_KEY_ID=\" + .AccessKeyId, \"export AWS_SECRET_ACCESS_KEY=\" + .SecretAccessKey,\"export AWS_SESSION_TOKEN=\" + .Token] | .[]")
docker run \
-e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
-e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
-e AWS_SESSION_TOKEN=$AWS_SESSION_TOKEN \
public.ecr.aws/aws-cli/aws-cli s3 ls
*Please change public.ecr.aws/aws-cli/aws-cli s3 ls according to your environment.
And it worked!
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
Why does it work?
CloudShell uses environment variables (tokens) to fetch temporary credentials from metadata to gain permissions.
curl \
-H "Authorization: $AWS_CONTAINER_AUTHORIZATION_TOKEN" \
-v $AWS_CONTAINER_CREDENTIALS_FULL_URI
Since the mechanism for retrieving these credentials cannot be used from within a container, running it directly results in Unable to locate credentials.
Instead, we retrieve them outside the container and pass them as environment variables to make the credentials available inside the container.
By the way, it is possible to pass the token for retrieving credentials, but I gave up because I couldn't communicate with the metadata endpoint.
$ docker run \
> -e AWS_CONTAINER_AUTHORIZATION_TOKEN=$AWS_CONTAINER_AUTHORIZATION_TOKEN \
> -e AWS_CONTAINER_CREDENTIALS_FULL_URI=$AWS_CONTAINER_CREDENTIALS_FULL_URI \
> public.ecr.aws/aws-cli/aws-cli s3 ls
Error when retrieving credentials from container-role: Error retrieving metadata: Received error when attempting to retrieve container metadata: Could not connect to the endpoint URL: "http://localhost:1338/latest/meta-data/container/security-credentials"
References
Discussion