Boto3使用旧的凭据 [英] Boto3 uses old credentials

查看:157
本文介绍了Boto3使用旧的凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用tkinter创建返回安全组的gui应用程序.当前,如果您要更改凭据(例如,如果您不小心输入了错误的凭据),则必须重新启动应用程序,否则boto3会继续使用旧的凭据.

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.

这是设置环境变量并启动boto3的代码的一部分.如果您是第一次输入正确的凭据,它会很好地工作.

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'],
)

凭据变量的设置使用:

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())

是否可以在不重新启动程序的情况下在boto3中使用不同的凭据?

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

推荐答案

您需要boto3.session.Session覆盖访问凭据.

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

只需执行此操作 参考 http://boto3.readthedocs.io/en/latest/reference/core/session.html

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")

基本上,您的代码没有什么变化.您只需传递会话,而不是直接传递boto3.client/boto3.resource

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')

这篇关于Boto3使用旧的凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆