How do I create a boto3 sessions that both uses a local AWS profile (by name), and assumes a AWS IAM role?

657 views Asked by At

This is not a duplicate. I have searched and could not find an exact match for this.


I have Python code running on my local machine.

I want to connect to AWS for the purpose of pulling a secret from AWS Secrets Management


On my local machine $HOME/.aws/config file, I have a profile configured.

[profile my-profile]
...

The profile is setup with the region, AWS account ID etc.

This is a known working profile that will connect to AWS.


I have configured an AWS IAM Role that is configured to restrict access to a secret stored in AWS Secrets.


On my local machine, in python code, I want to create a boto3 session and client that will:

  1. use the AWS local profile settings to connect to AWS
  2. and connect assuming the IAM role

so I can then pull the secret.


How do I create this boto3 session / client with this criteria?

I am not finding documentation on how to use both (local AWS profile by name and also assume AWS IAM role) for the specific purpose of pulling from AWS Secrets Management.


If anyone has actually done this, it would be greatly appreciated if code could be shared.


I have pulling a secret not assuming the role working fine on pulling a secret that is not restricted by a role.

Now I have created another secret restricted by a role and I cannot get this to work.

1

There are 1 answers

2
John Rotenstein On

To call AssumeRole(), you first need a set of credentials that have permission to call AssumeRole. These credentials will come from your ~/.aws/credentials file (optionally using a specific profile).

In response to an AssumeRole() call, AWS will return:

{
    'Credentials': {
        'AccessKeyId': 'string',
        'SecretAccessKey': 'string',
        'SessionToken': 'string',
        'Expiration': datetime(2015, 1, 1)
    },
    'AssumedRoleUser': {
        'AssumedRoleId': 'string',
        'Arn': 'string'
    },
    'PackedPolicySize': 123,
    'SourceIdentity': 'string'
}

This includes a different set of credentials that are associated with the IAM Role (instead of your IAM User). You must then use these credentials when making an API call 'as the assumed role'.

Think of it as entering a house with a front-door key then going to a table and picking up a car key. You can use the car key to drive the car that is outside the house, but you can't drive the car with the house key you used to enter the house.

  • House key = Your IAM User credentials
  • Picking up a Car key = Calling AssumeRole() and getting a new set of credentials (a new key)

You need to use the second set of credentials to drive the car.