gpt4 book ai didi

python-3.x - 以编程方式与 AWS SSO 建立 boto3 session

转载 作者:行者123 更新时间:2023-12-03 08:19:35 30 4
gpt4 key购买 nike

我尝试使用 boto3.session.Session(profile_name='foo') 建立 boto3 session ,但收到 UnauthorizedSSOTokenError错误:

botocore.exceptions.UnauthorizedSSOTokenError: The SSO session associated with this profile has expired or is otherwise invalid. To refresh this SSO session run aws sso login with the corresponding profile.

我尝试使用 subprocess.run("aws sso login --profile foo") 登录,但这会打开我的 Web 浏览器并提示手动确认。

如果您使用 AWS SSO,是否有任何方法可以以编程方式建立 boto3 session ?

也就是说,有没有办法避免手动确认?

最佳答案

我想在我的脚本中自动处理到期时的 SSO 重新身份验证,并且可以接受打开的浏览器窗口并(可能)提示用户授权设备访问。

最终结果是:

def establishSession(retry = True):
session = boto3.Session(profile_name=AWS_PROFILE)
sts = session.client('sts')
try:
identity = sts.get_caller_identity()
print(f"Authorized as {identity['UserId']}")
return session
except botocore.exceptions.UnauthorizedSSOTokenError:
if retry:
subprocess.run(['aws','sso', 'login', '--profile', AWS_PROFILE])
return establishSession(False)
else:
raise

get_caller_identity API 调用速度很快,并且不需要任何特殊权限。 https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html#STS.Client.get_caller_identity

关于python-3.x - 以编程方式与 AWS SSO 建立 boto3 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68285463/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com