How to transfer IAM roles from EC2 to docker


  1. First, add the permission “ec2:ModifyInstanceMetadataOptions” to the IAM role
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:ModifyInstanceMetadataOptions",
            "Resource": "arn:aws:ec2:*:00000000000:instance/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/Role": "MyAppRole"
                }
            }
        }
    ]
}
  1. Run modify-instance-metadata-options to increase hop limits
#!/bin/bash
set -euo pipefail
cd `/usr/bin/dirname $0`

_TOKEN=
for i in {1..10}
do
  _TOKEN=`curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 120"`
  if [ -z "$_TOKEN" ]; then
    sleep $i
  else
    break
  fi
done

_ID=`curl -s -H "X-aws-ec2-metadata-token: $_TOKEN" http://169.254.169.254/latest/meta-data/instance-id/`

aws ec2 modify-instance-metadata-options \
    --instance-id $_ID \
    --http-put-response-hop-limit 2 \
    --http-endpoint enabled


docker run --gpus all -it --rm \
--volume /home/ubuntu/app:/work:ro \
--workdir /work \
-p 80:80 \
my-container-name \
python3 /usr/local/bin/waitress-serve --port=80 app:app