I have been trying to understand for a while how IAM roles work.

Here’s how they work

  1. You attach an IAM role with the appropriate policies to an EC2 instance.
  2. The aws command line on the EC2 instance will get the security credentials from the EC2 meta-data

EC2 meta-data is fascinating. Turns out there is a special endpoint 169.254.169.254 which when access from an AWS instance will give you access to an API. In fact this works on both Linux and Windows.

curl 169.254.169.254

This will give you various API paths

Doing

curl 169.254.169.254/meta-data/latest/security/credentials

Gives you the IAM credentials(access key id and secret access key) that AWS is using. These credentials are not permanent and in fact are renewed every 5 minutes.

The AWS CLI as well as SDK are configured to search for credentials first under ~/.aws/credentials and then contact this endpoint to get the credentials.

When you use an EC2 instance with the attached IAM role, the AWS command line will use the above credentials to access AWS services.