承担IAM角色,然后在Python中生成预签名的URL [英] Assume IAM role and then generate pre-signed URL in Python

查看:233
本文介绍了承担IAM角色,然后在Python中生成预签名的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图承担IAM角色,然后通过生成预签名URL来使用Amazon S3,以便访问其中的S3存储桶. 这就是我在Python中配置代码的方式:

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)

这是正确的方法吗?

运行代码时出现错误botocore.exceptions.NoCredentialsError: Unable to locate credentials.

推荐答案

我对John的答案做了些微修改,现在它的工作符合预期:

I made slight modification to John's answer and now its working as expected:

    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,谢谢您的启发.

@John , thank you for the inspiration.

这篇关于承担IAM角色,然后在Python中生成预签名的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆