AWS: IAM: Role Chaining using Ruby SDK v3

Role Chaining is mentioned in the AWS Documentation but it is not clear exactly how you are meant to implement it in practice. It is used when you want to use one role to assume another role, which may be used to indicate the type of task you are performing as the app or may be because you are moving between multiple accounts.

To achieve this the basic flow is:

  1. Establish STS Client #1
  2. AssumeRole of Role A, associating with Client #1
  3. Establish STS Client #2 using credentials retrieved from above AssumeRole command
  4. AssumeRole of Role B

Suppose we have want to use Role A to access Role B. The code to do so looks something like this:

# establish sts client
sts_client = Aws::STS::Client.new({ region: 'ap-southeast-2' })
# get credentials for role A
credentials = Aws::AssumeRoleCredentials.new( client: sts_client, role_arn: role_a_arn, role_session_name: 'my-session' )
# establish second STS client
sts_client_privileged = Aws::STS::Client.new({ region: 'ap-southeast-2', credentials: credentials })
# get role B credentials
credentials = Aws::AssumeRoleCredentials.new( client: sts_client, role_arn: role_b_arn, role_session_name: 'my-session' )

One gotcha is that you need to ensure both the sts:AssumeRole permission is granted to any role that is attempting to assume a role (above that would be the initial Instance Role and Role A) and that the Trust Relationships are established. Trust Relationships say which ARNs or Services are allowed to assume a role. Both must be present for the above to work.

Also note this assumes the code is running on an EC2 instance that has an instance role which allows it to assume Role A in the first place.

Leave a comment if that doesn’t make sense and I’ll do my best to help or clarify.


Leave a Reply

Your email address will not be published. Required fields are marked *