Boto3 uses old credentials

I use tkinter to create a GUI application that returns security groups. Currently, if you want to change your credentials (for example, if you accidentally entered the wrong ones), you will have to restart the application, otherwise boto3 will continue to use the old credentials.

I'm not sure why he continues to use the old credentials because I am starting everything up again using the credentials I have currently entered.

This is a piece of code that sets environment variables and starts boto3 . It works great if you enter the correct credentials for the first time.

 os.environ['AWS_ACCESS_KEY_ID'] = self.accessKey os.environ['AWS_SECRET_ACCESS_KEY'] = self.secretKey self.sts_client = boto3.client('sts') self.assumedRoleObject = self.sts_client.assume_role( RoleArn=self.role, RoleSessionName="AssumeRoleSession1" ) self.credentials = self.assumedRoleObject['Credentials'] self.ec2 = boto3.resource( 'ec2', region_name=self.region, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'], ) 

Credential variables are set using:

 self.accessKey = str(self.AWS_ACCESS_KEY_ID_Form.get()) self.secretKey = str(self.AWS_SECRET_ACCESS_KEY_Form.get()) self.role = str(self.AWS_ROLE_ARN_Form.get()) self.region = str(self.AWS_REGION_Form.get()) self.instanceID = str(self.AWS_INSTANCE_ID_Form.get()) 

Is there a way to use different credentials in boto3 without restarting the program?

+5
source share
2 answers

You need boto3.session.Session to overwrite access credentials.

Just make this link http://boto3.readthedocs.io/en/latest/reference/core/session.html

 import boto3 # Assign you own access mysession = boto3.session.Session(aws_access_key_id='foo1', aws_secret_access_key='bar1') # If you want to use different profile call foobar inside .aws/credentials mysession = boto3.session.Session(profile_name="fooboar") # Afterwards, just declare your AWS client/resource services sqs_resource=mysession.resource("sqs") # or client s3_client=mysession.client("s3") 

Basically, a slight change in your code. you just go through the session instead of direct boto3.client / boto3.resource

 self.sts_client = mysession.client('sts') 
+4
source

Of course, just create different sessions from the botocore.session.Session object for each credential set:

 import boto3 s1 = boto3.session.Session(aws_access_key_id='foo1', aws_secret_access_key='bar1') s2 = boto3.session.Session(aws_access_key_id='foo2', aws_secret_access_key='bar2') 

You can also use the set_credentials method to save 1 session on-the-fly with changes:

 import botocore session - botocore.session.Session() session.set_credentials('foo', 'bar') client = session.create_client('s3') client._request_signer._credentials.access_key u'foo' session.set_credentials('foo1', 'bar') client = session.create_client('s3') client._request_signer._credentials.access_key u'foo1' 
+3
source

All Articles