February 9, 2017

How to assume ec2 instance role

I just spent two hours of my life trying to get AssumeRole working. And that was not the first time. So I hope this article saves someone elses time or reminds me again in six months how to do this properly.

Assume what?

To work with AWS resources you can create a user, assing roles to it or use inline policies attached to that user. This works if you have couple of users and few resources to work with. But once your application count reaches two digits it may become more complicated.

You should rotate access keys often, make sure that all users have correct permissions and that they couldn’t access parts of your account that you wish to keep secured. Add some developers, multiple environments and access levels to the mix and all this becomes little annoying to manage.

But each ec2 instance has a role since it was created. You might as well manage this roles access and forget about managing access keys manually. This sounds like a nice solution, until you start to think about developing and testing your application locally. You localhost does not have that role.

This is where AWS Security Token Service comes into play.

An example

Start by looking up your role you like to assume and note down it’s ARN (arn:aws:iam::123456789:role/ec2-my-server)

Create a user for development environment (IAM) and note it’s ARN (something like arn:aws:iam::123456789:user/developer).

Add an inline policy, use generator or paste in something like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1486663415000",
            "Effect": "Allow",
            "Action": [
                "sts:AssumeRole"
            ],
            "Resource": [
                "arn:aws:iam::123456789:role/ec2-my-server"
            ]
        }
    ]
}

Now the next part is the tricky one. I tested the policy with Policy Simulator but could not figure out why I see the following using awscli:

$ aws sts assume-role --role-arn arn:aws:iam::123456789:role/ec2-my-server --role-session-name testSession1

A client error (AccessDenied) occurred when calling the AssumeRole operation: User: arn:aws:iam::123456789:user/developer is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::123456789:role/ec2-my-server

The problem is in missing Trust Relationship. Check again your server role and add your user ARN under Edit Trust Relationships:

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "ec2.amazonaws.com",
                "AWS": "arn:aws:iam::123456789:user/developer"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

VoilĂ .

Powered by Hugo & Kiss.