我希望创建一个Python进程来在运行时刷新临时AWS凭证(有效期为30分钟),以确保我的代码可以连续运行30分钟以上。
什么是RefreshableCredentials?如何使用?
经过一番摸索,我终于得出结论,没有记录botocore和boto3类。
我查看了源代码,并实现了适用于我的用例的解决方案。将其发布在这里供其他人参考。
class AWSCredsRefresh:
def run(self):
session = get_session()
cred_provider = session.get_component('credential_provider')
cred_provider.insert_before('env', CustomCredentialProvider())
boto3_session = Session(botocore_session=session)
#Perform AWS operations with boto3_session
class CustomCredentialProvider(CredentialProvider):
CANONICAL_NAME = "custom-creds"
def __init__(self):
def load(self):
#These creds will be automatically refreshed using the _refreh method if the current creds are going to expire in 15 mins or less
creds = DeferredRefreshableCredentials(refresh_using=self._refresh, method="sts-assume-role",)
return creds
def _refresh(self):
#Refresh your AWS creds using custom process
response = self._custom_aws_cred_refresh()
credentials = {
"access_key": response.get("AccessKeyId"),
"secret_key": response.get("SecretAccessKey"),
"token": response.get("SessionToken"),
"expiry_time": response.get("Expiration").isoformat(),
}
return credentials
def _custom_aws_cred_refresh(self):
#Your custom AWS cred refresh code
return response
if __name__ == '__main__':
obj = AWSCredsRefresh()
obj.run()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句