5
5

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.

ECS + AWS SDK for Python(boto3)でS3へファイルPUT

5
Posted at

ECSのコンテナからS3へPUTするには

  1. Dockerfileでboto3をインストール
  2. boto3を使用したpythonのコーディング
  3. コンテナ実行のロールにS3の権限を付与

※通信環境について
 もちろん、プライベートサブネットにおくなら、NATかEndpointで
 各種サービスに接続できるようにする必要はあります。 

1.Dockerfile

boto3のインストールを記載

Dockerfile
FROM python:3.6.8-alpine3.8
WORKDIR /temp
COPY ./test.py .
RUN pip install boto3
CMD [ "python", "./test.py" ]

2.pythonのコーディング

boto3を使用してS3へPUT

参考URL

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html

test.py
import boto3
import hashlib
import base64

# S3オブジェクトを作成
s3 = boto3.resource('s3',region_name='ap-northeast-1')
bucket = 'testbucket'
key = 'test.csv'
obj = s3.Object(bucket,key)

# ファイルコンテンツを設定
file_contents = 'testdayo'

# ファイルのMD5を取得
md5 = hashlib.md5(file_contents.encode()).digest()

# MD5をbase64・strに変換
b64md5 = base64.b64encode(md5).decode()

# ファイルをS3のバケットへput
obj.put( Body=file_contents, ACL='private', StorageClass='STANDARD', ContentMD5=b64md5) 

putのパラメーターには下記を設定していますが、必要に応じて公式のDocsをご確認くださいませ。
①Body:ファイル内容
②ACL :オブジェクトのACL
③StorageClass:ストレージクラス
④ContentMD5:チェックサム用のMD5の値

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?