Jwan622
Jwan622

Reputation: 11639

Assuming an IAM role in python, how to do this?

My aws config has a few profiles:

cat config

[default]
region = us-west-2

[profile sandbox]
region = us-west-2
role_arn = arn:aws:iam::11111111111:role/team-role
source_profile = default

[profile cat]
role_arn = arn:aws:iam::22222222222:role/data-systems-role
region = us-west-2
source_profile = default

When I run this command from the CLI, I can assume the cat role by typing --profile at the end.

aws secretsmanager get-secret-value --secret-id "prod/Aurora/klondike/twou_id_ro" --profile dsci

But I don't know how to do this in python code. I have this code but it seems to be assuming the wrong role:

 session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name
    )


{'Error': {'Message': 'User: arn:aws:sts::3333333333:assumed-role/.../[email protected] is not authorized to perform: secretsmanager:GetSecretValue on resource: arn:aws:secretsmanager:us-west-2...

I think my code is assuming the default? How do I get my python code to assume the cat role? When a role is assumed, it gets temporary creds from sts right? Is that what is going on?

Upvotes: 0

Views: 3502

Answers (1)

jarmod
jarmod

Reputation: 78613

Here is what you should do. In your code, use the default session constructor, for example:

session = boto3.Session()
client = session.client(...)

When running on EC2 with an IAM role, your app will use credentials associated with that IAM role.

Now, ideally, you want to write code that also works on your laptop without any changes. And you can do that. The above code will work fine. It will pull credentials from your AWS_xxx environment variables or from your default AWS credentials profile.

If you're running on your laptop and you would prefer not to use your default AWS credentials profile but instead use a different profile that you set up specifically to assume an IAM role, like your cat and sandbox profiles, then simply provide that profile in your environment, for example:

AWS_PROFILE=sandbox python3 my-boto-app.py

Or:

export AWS_PROFILE=sandbox
python3 my-boto-app.py

But I prefer the former because the AWS_PROFILE environment variable assignment is temporary.

Finally, please read the boto3 credentials docs. They are helpful.

Upvotes: 2

Related Questions