AWS allows resources like EC2 instances to have a IAM role assigned to them. In effect, this gives applications run on the EC2 instance the permissions of that role. This means that neither the code itself, nor the process running the code, need to supply any credentials or keys, which is very convenient when designing deployment practices.

In this blog post we'll look at how roles can be assigned to EC2 instances and then used to assume secondary roles.

Assigning Roles to EC2 Instances

We'll start with an EC2 instance that has no roles and an IAM role called ExampleRole that has no policies attached to it. Roles can be assigned to an existing EC2 instance with the command:

You can assign a role during the creation of an EC2 instance using the IAM role drop down menu.

Creating Trust Policies

Before an EC2 instance can make use of an assigned role, the role needs to give the EC2 service permission to do so. This is done by assigning the following policy to the ExampleRole trust relationship.

To use these keys, it is common to assign them to environment variables.

JSON Field

Environment Variable

AccessKeyId

AWS_ACCESS_KEY_ID

SecretAccessKey

AWS_SECRET_ACCESS_KEY

Token

AWS_SESSION_TOKEN

Using Role Credentials with the AWS CLI

Although it is possible to query the instance metadata and create environment variables from the keys, a good number of tools already know how to query the instance metadata for themselves. The AWS CLI is a good example of this.

Without creating any environment variables or running aws configure to save any keys in a local configuration file, running the command:

In this case the AWS CLI knows to generate keys from the instance metadata, and will do so automatically if no other keys, environment variables or configuration files are present.

Assuming a Secondary Role

From the role assigned to the EC2 instance, we can then assume a secondary role. Secondary roles might be used for testing permissions, or running processes with additional permissions in the same way you might use the sudo command.

Let's assume that we have a second role called ExampleAssumedRole that we would like to assume from ExampleRole.

The first step is to give ExampleRole the permissions to assume ExampleAssumedRole. This is done with the following policy on ExampleRole:

Conclusion

AWS offers a flexible security system that allows roles to be assigned to EC2 instances, and for secondary roles to be assumed. This allows for permissions to be assigned without embedding keys in applications or scripts, and for processes to be run with different privileges much as you would with the sudo command.