Farhan.K Farhan.K - 7 months ago 74
Python Question

Boto3 uses old credentials

I am using

tkinter
to create gui application that returns the security groups. Currently if you want to change your credentials (e.g. if you accidentally entered the wrong ones) you would have to restart the application otherwise
boto3
would carry on using the old credentials.

I'm not sure why it keeps using the old credentials because I am running everything again using the currently entered credentials.

This is a snippet of the code that sets the environment variables and launches
boto3
. It works perfectly fine if you enter the right credentials 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'],
)


The credentials 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?

Answer

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

Just do this reference 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, little change to your code. you just pass in the session instead of direct boto3.client/boto3.resource

self.sts_client = mysession.client('sts')