8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

boto3でS3オブジェクトのpublicなURLを取得する方法

Posted at

対象読者

boto3が提供しているAPIが get_presigned_url しかなくて困った仔羊に向けて :sheep:

S3オブジェクトのpublicなURLを取得する場合のコード

aws.py
import boto3

s3 = boto3.client('s3')

def get_public_url(bucket, target_object_path):
    """
    対象のS3ファイルのURLを取得する

    Parameters
    ----------
    bucket: string
        S3のバケット名
    target_object_path: string
        取得したいS3内のファイルパス

    Returns
    ----------
    url: string
        S3上のオブジェクトのURL
    """
    bucket_location = s3.get_bucket_location(Bucket=bucket)
    return "https://s3-{0}.amazonaws.com/{1}/{2}".format(
        bucket_location['LocationConstraint'],
        bucket,
        target_object_path)

LocationConstraintの取得でAccess Deniedが出る場合

S3バケットのバケットポリシーを以下に設定する

bucket_policy.json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AddPerm",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetBucketLocation"
            ],
            "Resource": [
                "arn:aws:s3:::[バケット名]/*",
                "arn:aws:s3:::[バケット名]"
            ]
        }
    ]
}

参考文献

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?