如何使用Python Boto3库修改AWS角色的最大会话时长
解决方案:角色会话过期与S3 GetObjectAttributes报错处理
一、修改角色会话时长,解决ExpiredToken错误
1. 调整角色的最大允许会话时长
角色默认最大会话时长为1小时,需先将其修改为你需要的时长(最多12小时):
- 登录IAM控制台,找到目标角色
- 进入「信任关系」标签页,点击「编辑信任策略」
- 在策略文档中添加
MaxSessionDuration参数,值为秒数(例如43200代表12小时):{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::ACCOUNT-ID:user/USER-NAME" }, "Action": "sts:AssumeRole", "Condition": {}, "MaxSessionDuration": 43200 } ] } - 保存策略,完成角色最长会话时长更新
2. 在Boto3中指定会话时长
方式一:主动调用STS AssumeRole
如果通过STS主动获取角色凭证,需在调用时传入DurationSeconds参数(值不能超过角色设置的最大时长):
import boto3 sts_client = boto3.client('sts') response = sts_client.assume_role( RoleArn='arn:aws:iam::ACCOUNT-ID:role/YOUR-ROLE-NAME', RoleSessionName='YOUR-SESSION-NAME', DurationSeconds=43200 # 时长不超过角色的MaxSessionDuration ) # 使用返回的凭证创建S3客户端 s3_client = boto3.client( 's3', aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'] )
方式二:通过AWS配置文件自动扮演角色
在~/.aws/config的对应profile中添加duration_seconds参数:
[profile your-profile-name] role_arn = arn:aws:iam::ACCOUNT-ID:role/YOUR-ROLE-NAME source_profile = your-source-profile duration_seconds = 43200
二、修复GetObjectAttributes报错
你遇到的InvalidArgument错误是因为指定的属性名不符合要求,合法属性名包括:
ObjectSizeLastModifiedETagChecksumStorageClassObjectPartsBucketKeyEnabled
确保属性名采用驼峰式拼写,修改后的代码示例:
boto_client.get_object_attributes( Bucket='bucket_name', Key='secret_access_key', ObjectAttributes=['LastModified', 'ObjectSize'] )
另外,该API要求botocore版本>=1.26.0,若版本过低请升级:
pip install --upgrade botocore boto3
内容的提问来源于stack exchange,提问作者300
相关产品推荐
相关产品推荐

