We are using Python boto3 library and are assuming a role through a profile. The reason for assuming role is S3 bucket we want to access is accessible only through that role. Now I see aws profile's AccessToken doesn't expire but the role we are assuming using this profile does expire in 1 hour. This results in following error:
An error occurred (ExpiredToken) when calling the ListObjectsV2 operation: The provided token has expired
I have found in AWS documentation that there is option to do this but it's not clear. I tried getting DurationSeconds
parameter from session object or client object but couldn't find it.
I tried
boto_client.get_object_attributes(Bucket='bucket_name', Key='secret_access_key', ObjectAttributes=['LastModified'])`
but get error:
botocore.exceptions.ClientError: An error occurred (InvalidArgument) when calling the GetObjectAttributes operation: Invalid attribute name specified.
You can specify the session duration when you assume the role with DurationSeconds
:
import boto3
creds = boto3.client('sts').assume_role(
RoleArn="arn:aws:iam::0000000000000000:role/custom-role",
RoleSessionName="AssumeRoleSession1",
DurationSeconds=10800 # 3 hours
)['Credentials']
session = boto3.Session(
aws_access_key_id=creds['AccessKeyId'],
aws_secret_access_key=creds['SecretAccessKey'],
aws_session_token=creds['SessionToken']
)
s3_client = session.client('s3')
...
DurationSeconds
can be up to 43200 (12 hours)