EC2 Instance assume role in other accounts


Besides IAM users, some AWS services can also assume roles. Here is the example of granting assume role permission to a EC2 instance.

The scenario is that I have two accounts:

  • In account A, I created a role (e.g RoleForB) to trust account B, and add a IAM policy to allow it to perform some read operations in account A. e.g ReadOnlyAccess
  • In account B, I created a role (e.g AssumeRoleInA) and add the policy to allow it to assume the role that is created in account A.
  • Associate a EC2 instance to the IAM role (AssumeRoleInA)

Let’s have a look at the configurations:

In account A, it builds the trust to account B by creating the role named RoleForB and attaching ReadOnlyAccess permission.

{
    "Version": "2012-10-17",
    "Statement": {
		"Effect": "Allow",
		"Principal": {"AWS": "arn:aws:iam::Account_B_ID:root"},
		"Action": "sts:AssumeRole"
	}
}

In account B, create a role named AssumeRoleInA then add a policy to allow it to assume the role named RoleForB in account A.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "sts:AssumeRole",
      "Resource": [
        "arn:aws:iam::Account_A_ID:role/RoleForB"
      ]
    }
  ]
}

Create a new EC2 instance, and associate it with the IAM role named AssumeRoleInA.

{
    "Version": "2012-10-17",
    "Statement": {
		"Effect": "Allow",
		"Principal": {"Service": "ec2.amazonaws.com"},
		"Action": "sts:AssumeRole"
	}
}

Now login into this instance to assume the role in Account A. The following command will return the the access key, secret key and security token.

aws sts assume-role --role-arn "arn:aws:iam::Account_A_ID:role/RoleForB" 
--role-session-name "EC2FromB"
Advertisement

2 thoughts on “EC2 Instance assume role in other accounts

  1. Thank you for sharing your elegant solution. Worked for me as a charm to update production route53 and load balancer from build server in dev account.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s