Mark Reed
Mark Reed

Reputation: 95252

How to get a boto3 STS client without any authentication attempt?

I'm using this code to assume an Amazon Web Services role via SAML authentication:

client = boto3.client('sts', region_name = region)
token = client.assume_role_with_saml(role, principal, saml)

As documented here, the assume_role_with_saml call does not require the use of AWS security credentials; all the auth info is contained in the parameters to the call itself. Nonetheless, if I have auth-related AWS_ environment variables set, the call to boto3.client() immediately tries to use them to authenticate. Usually, I have AWS_PROFILE set, and the reason I'm running this code is because the named profile's security token has expired, so the call fails, and I have to unset AWS_PROFILE and try again.

I can of course manually go through os.environ looking for and deleting relevant variables before the call to boto3.client(), but I'm wondering if there's any cleaner way to say "Hey, Boto, just give me an STS client object without trying to authenticate anything, OK?"

Upvotes: 2

Views: 3983

Answers (2)

Mark Reed
Mark Reed

Reputation: 95252

By examining the boto3 and botocore code, I worked out a solution, but I'm not sure it's an improvement over unsetting the environment variables:

import boto3, botocore
bs = botocore.session.get_session({ 'profile': ( None, ['', ''], None, None ) })
bs.set_credentials('','','')
s = boto3.session.Session(botocore_session = bs)
client = s.client('sts', region_name = region)

Accepting my own answer for now, but if anyone has a better idea, I'm all ears.

Upvotes: 0

tzaman
tzaman

Reputation: 47790

From this response on GitHub, here's how to set up a client that won't attempt to sign outgoing requests with IAM credentials:

import boto3                      
from botocore import UNSIGNED     
from botocore.config import Config

client = boto3.client('sts', region_name=region, config=Config(signature_version=UNSIGNED))

Upvotes: 2

Related Questions