2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

boto3でbucket-owner-full-controlを使うには

Posted at

はじめに

クロスアカウントでs3にファイルをアップロードする際に、boto3でbucket-owner-full-controlを付ける方法について、記載していきます。

bucket-owner-full-controlとは
これを指定することで、アカウントをまたいでS3にオブジェクトをアップロードする際、所有者をアップロードのアカウントにすることができる。

デフォルトは、アップロードのアカウントが、オブジェクトの所有者になっている。

参考:どうやってbucket-owner-full-control ACL を Amazon S3 内のオブジェクトに追加するんですか?

コード

ExtraArgsとして、{"ACL": "bucket-owner-full-control"}を指定することで、所有者として、アップロード先のアカウントを指定できます。

s3.py
import boto3
import logging
from botocore.exceptions import ClientError

class S3Client:
    """
    s3 utility client that currently has the following features:
        Upload to s3
    """

    def __init__(self, aws_account=None, aws_access_key_id=None, aws_secret_access_key=None):
        if aws_account == 'OurAccount':
            self.client = boto3.client(
                's3',
                aws_access_key_id = aws_access_key_id,
                aws_secret_access_key = aws_secret_access_key
            )
        self.client = boto3.client('s3')
    
    def upload_file(self, file_name, bucket, object_path):
        ExtraArgs =  {"ACL": "bucket-owner-full-control"}
        try:
            self.client.upload_file(file_name, bucket, object_path, ExtraArgs=ExtraArgs)
        except ClientError as e:
            logging.error(e)
            return False
        return True

この修正を行うことで、今までS3のファイルを取得する際に出ていた以下のエラーが解消されました :clap:

fatal error: An error occurred (403) when calling the HeadObject operation: Forbidden

参考にした公式ドキュメント

ALLOWED_UPLOAD_ARGSの中にACLが含まれていたので、ExtraArgsとして指定できました。

終わりに

同じようなことに悩んでいる方の解決に役立ったら幸いです:blush:

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?