I am trying to assume an IAM role and then use Amazon S3 by generating a presigned URL in order to access an S3 bucket in it. This is how I have configured my code in Python :
def create_dynamicurl(key, expiration):
client = boto3.client('sts')
assumed_role_object = client.assume_role(DurationSeconds=3600,RoleArn='arn:aws:iam::123456789555:role/sample-S3AssumeRole',RoleSessionName='sampleSession',)
temp_credentials = assumed_role_object['Credentials']
s3_resource = boto3.resource('s3' , aws_access_key_id=temp_credentials['AccessKeyId'],aws_secret_access_key=temp_credentials['SecretAccessKey'],aws_session_token=temp_credentials['SessionToken'])
bucket_name = s3_resource.bucket
params = {
'Bucket': bucket_name,
'Key': key
}
s3 = boto3.client('s3')
url = s3.generate_presigned_url('get_object', Params=params, ExpiresIn=expiration)
log.info('******URL******: %s' % url)
return (url)
Is this the correct approach??
I was getting the error botocore.exceptions.NoCredentialsError: Unable to locate credentials
while running the code.
After you Assume Role, you can use the credentials like this:
I didn't test it, but you should get the general idea.
I made slight modification to John's answer and now its working as expected:
@John , thank you for the inspiration.