In the previous post about Access & Secret Keys I emphasized that those keys – static keys – should never be used in production and in fact they should never leave your laptop. But what if you need to call the AWS services from scripts or programs running on an EC2 instance?

In a typical scenario such a script is called either by a scheduler (cron) or by another program like CI/CD tool (Jenkins) to automatically perform a task that needs certain AWS privileges. Say it has to upload a newly build package to an S3 bucket at the final stage of Jenkins run or it shut down all non-production EC2 instances in the evening and restart them in the morning.
The answer is – assign IAM Role to the EC2 Instance

EC2 Instance Role provides the Instance access to a set of IAM Credentials and – if the associated IAM Policies permit – access to AWS services.

Static IAM Keys EC2 Instance Keys
Never expire Limited lifetime
Generated manually through IAM Generated automatically when needed
Stored in $HOME/.aws/config – risk of leak Never stored anywhere – limited risk of leak

Guess which keys are more secure to use? 🙂

Let’s first demonstrate how to enable EC2 Instance Keys and then how to use them.

Create IAM Role

Go to DashboardIdentity and Access Management (IAM) ➞ Roles and click Create New Role button.

Give it a name, for example Test-Role and confirm.

The next step is Select Role Type. Roles can have various purposes and hence various types. For our needs select Amazon EC2Allows EC2 instances to call AWS on your behalf.


For now don’t attach any policies. We will do that later.

On the overview page confirm that everything is as expected and click Create Role.


The new Test-Role will show up in the list of IAM roles.

Launch EC2 Instance with the IAM Role attached

I assume that you know how to create EC2 instances and will only point out the Role-specific settings. Start creating EC2 instance as usual, pick your AMI, select the appropriate instance type and configure the subnet. Now it’s time to select the IAM Role we have just created above.


Note that you can configure the IAM Role only when launching the instance. It can’t be added later!

The best practice is to create a new role for each instance you are starting (or for group of similar instances in case of auto-scaling). It can be empty, like we did now, but it’s there and if needed later you can easily attach the required policies. You can’t, however, attach an IAM Role to EC2 instance once it’s created. Best to give each EC2 an empty role from the start. This is easily done with automation scripts or CloudFormation templates.

Go through the rest of the configuration and Launch your instance.

In the next post I will describe how to use the EC2 Instance Credentials.