はじめに
クロスアカウントで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のファイルを取得する際に出ていた以下のエラーが解消されました
fatal error: An error occurred (403) when calling the HeadObject operation: Forbidden
参考にした公式ドキュメント
ALLOWED_UPLOAD_ARGS
の中にACLが含まれていたので、ExtraArgs
として指定できました。
終わりに
同じようなことに悩んでいる方の解決に役立ったら幸いです