Instance Roles and Profiles

Having an EC2 instance or group of instances assume a role is the best practice way to assign permissions to them.

When a role is attached to an instnce what happens under the hood is that an Instance Profile (a wrapper around IAM roles) is created with that role attached and is assigned to that instance. Instance profiles are not visible from the UI console. When using the CLI, CloudFormation or the APIs you need to create an Instance Profile with that role first.

The temporary credentials that the role gives access to can be inspected using the metadata endpoint.

Getting role credentials using the metadata endpoint
[ec2-user@i-0b0d190f9e5275929 ~]$ TOKEN=`curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"`

[ec2-user@i-0b0d190f9e5275929 ~]$ curl -H "X-aws-ec2-metadata-token: $TOKEN"   http://169.254.169.254/latest/meta-data/iam/info
{
  "Code" : "Success",
  "LastUpdated" : "2024-05-16T16:25:20Z",
  "InstanceProfileArn" : "arn:aws:iam::123456789012:instance-profile/myRole",
  "InstanceProfileId" : "AIPA2S6TZNPQ67BDPYHXF"
}

[ec2-user@i-0b0d190f9e5275929 ~]$ curl -H "X-aws-ec2-metadata-token: $TOKEN"   http://169.254.169.254/latest/meta-data/iam/security-credentials/myRole
{
  "Code" : "Success",
  "LastUpdated" : "2024-05-16T16:25:16Z",
  "Type" : "AWS-HMAC",
  "AccessKeyId" : "ASIA2S6TZNPQ6N6CVNDT",
  "SecretAccessKey" : "1/BXi2Xi4s0g1q6TrKh2CqDWOFLh3Egc8jKtYrxd",
  "Token" : "IQoJb3JpZ2lu...ZvTGN2lodA=",
  "Expiration" : "2024-05-16T23:00:20Z"
}