我尝试承担IAM角色,然后通过生成预签名URL来使用Amazon S3,以便访问其中的S3存储桶。 这就是我在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)
这是正确的方法吗?
运行代码时出现错误botocore.exceptions.NoCredentialsError: Unable to locate credentials
。
答案 0 :(得分:0)
担任角色后,可以使用以下凭据:
sts_client = boto3.client('sts')
assumed_role_object = sts_client.assume_role(DurationSeconds=3600,RoleArn='arn:aws:iam::123456789555:role/sample-S3AssumeRole',RoleSessionName='sampleSession',)
temp_credentials = assumed_role_object['Credentials']
session = Session(aws_access_key_id = temp_credentials['AccessKeyId'],
aws_secret_access_key = temp_credentials['SecretAccessKey'],
aws_session_token = temp_credentials['SessionToken'])
assumed_client = session.client('s3')
url = assumed_client.generate_presigned_url('get_object', Params=params, ExpiresIn=expiration)
我没有测试它,但是您应该了解一般的想法。
答案 1 :(得分:0)
我对John的答案做了些微修改,现在它的工作符合预期:
def create_dynamicurl(bucket ,key, expiration):
client = boto3.client('sts')
assumed_role_object = client.assume_role(DurationSeconds=3600,RoleArn=123456789555:role/sample-S3AssumeRole',RoleSessionName='sampleSession',)
temp_credentials = assumed_role_object['Credentials']
session = boto3.session.Session(aws_access_key_id=temp_credentials['AccessKeyId'],
aws_secret_access_key=temp_credentials['SecretAccessKey'],
aws_session_token=temp_credentials['SessionToken'])
s3_resource = session.resource('s3')
bucket_name = s3_resource.Bucket(bucket).name
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)
@John,谢谢您的启发。