How on earth does this solve the problem of hardcoded AWS API keys? Well, something really interesting happens when you assign a role to an EC2 instance. The metadata for that instance will return a set of short-lived API keys. You can retrieve these keys by sending an HTTP request to the metadata URL (this is a service EC2 instances can use to fetch information about themselves):
http://169.254.169.254/latest/meta-data/iam/security-credentials/<role name>
The output of a curl request to this URL will look something like this:
{
"Code" : "Success",
"LastUpdated" : "2017-02-17T11:14:23Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "AAAAAAAAAAAAAAAAAAAA",
"SecretAccessKey" : "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
"Token" : "token",
"Expiration" : "2017-02-17T12:14:23Z"
}
If you take the AccessKeyId and SecretAccessKey returned in the response, you can use them to query the AWS API. The policies applied to the instance based on the role assigned to it will determine exactly what API actions the instance is able to perform using these keys.
The really fun part is that you don't have to worry too much about handling these keys at all (although it's really useful to know how all this works under the hood). For example, the AWS CLI tools will automatically fetch these keys for you prior to running any CLI commands. The same goes for the AWS SDKs.
Take a scenario where your developers are building an application that needs to fetch files from S3. As long as they are using the AWS SDK to do this and the application is running on an EC2 instance that has been assigned a role containing a policy that allows files to be fetched from S3, then no credentials are required by the application whatsoever! The SDK will take care of the queries to the metadata service for you.
The AWS SDKs are available for almost every widely used language, so there's no excuse for keeping hardcoded AWS credentials in config files or source code.
You will see your instances roles listed in the IAM console under the Roles section:
Clicking on the role will reveal further details, such as the policies that have been assigned to it: