[英]Creating a function to assume an AWS STS role in PowerShell $PROFILE
[英]AWS Assume Role STS
我尝试每天使用 Python 访问我的 S3 存储桶,但我的会话经常过期。 此站点上有人建议我使用“假定角色”STS 脚本重新建立连接。 我找到了一个使用它的脚本,但出现以下错误。 仅供参考,我在 .aws 文件夹中有我的凭据文件。
"botocore.exceptions.NoCredentialsError: Unable to locate credentials"
下面是我的代码:
import boto3
# The calls to AWS STS AssumeRole must be signed with the access key ID
# and secret access key of an existing IAM user or by using existing temporary
# credentials such as those from another role. (You cannot call AssumeRole
# with the access key for the root account.) The credentials can be in
# environment variables or in a configuration file and will be discovered
# automatically by the boto3.client() function. For more information, see the
# Python SDK documentation:
# http://boto3.readthedocs.io/en/latest/reference/services/sts.html#client
# create an STS client object that represents a live connection to the
# STS service
sts_client = boto3.client('sts')
# Call the assume_role method of the STSConnection object and pass the role
# ARN and a role session name.
assumed_role_object=sts_client.assume_role(
RoleArn="ARNGOESHERE",
RoleSessionName="AssumeRoleSession1"
)
# From the response that contains the assumed role, get the temporary
# credentials that can be used to make subsequent API calls
credentials=assumed_role_object['Credentials']
# Use the temporary credentials that AssumeRole returns to make a
# connection to Amazon S3
s3_resource=boto3.resource(
's3',
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken'],
)
# Use the Amazon S3 resource object that is now configured with the
# credentials to access your S3 buckets.
for bucket in s3_resource.buckets.all():
print(bucket.name)
您将在这里有 2 个选项:
创建具有编程访问权限的单独用户。 这将是永久性的,凭证不会过期。 通常出于安全考虑,组织中的开发人员不允许这样做。 参考步骤: https ://aws.amazon.com/premiumsupport/knowledge-center/create-access-key/
如果您不允许通过上述方法获得永久访问令牌,那么您可以将令牌到期持续时间从默认值(1 小时)增加到最长 12 小时,以跳过大约每小时重新运行一次 PowerShell 脚本。 为此,您需要修改您运行的 PowerShell 脚本“saml2aws”以获取凭据。
为 assume_role_with_saml() 方法添加 arg 'DurationSeconds'。 参考: https ://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts.html#STS.Client.assume_role_with_saml
response = client.assume_role_with_saml(
RoleArn='string',
PrincipalArn='string',
SAMLAssertion='string',
PolicyArns=[
{
'arn': 'string'
},
],
Policy='string',
DurationSeconds=123
)
您可以在此处输入的最长持续时间取决于您角色的最长会话持续时间设置。 您可以在 AWS 控制台的 IAM>Roles>{RoleName}>Summary>MaximumSessionDuration 中查看它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.