LoginSignup
6

More than 1 year has passed since last update.

LambdaでS3のファイルを読み書きする

Last updated at Posted at 2022-04-04

Lambda(Python)からS3へファイルをアップロードしたり、読み書きしたりすることがあったので書き記しておきます。

権限周りの話は以前こちらに書いてあるので参考にして下さい ↓↓↓

Client APIとResource APIの違い

・Client APIはレスポンスが辞書型なので必要な情報を取り出しにくい
・Client APIはHTTP API 操作との 1 対 1 のマッピングが提供される
・Resource APIの方がオブジェクト指向っぽく書ける
・Resource APIが用意されていないことがあるサービスもある

* Resource APIはresponse.bodyというようにオブジェクトを取得してから属性を参照できると書いてあったが自分はなぜかレスポンスが辞書型であった。よく分からない。

S3にファイルをアップロードする

* 上書きするときもs3.put_objectで行う
* バケットポリシーに"Action": "s3:PutObject"を追記する

boto3.clientの場合

import json
import boto3
from datetime import datetime

s3 = boto3.client('s3')

def lambda_handler(event, context):
    file_contents = '[{"name": "tomoki","age": 21},{"name": "yamaoka","age": 21}]'
    bucket = 's3-backet-redshift'
    key = 'test_' + datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.json'
    response = s3.put_object(Body=file_contents, Bucket=bucket, Key=key)
    return response

boto3.resourceの場合

import json
import boto3
from datetime import datetime

s3 = boto3.resource('s3')

def lambda_handler(event, context):
    file_contents = '[{"name": "tomoki","age": 22},{"name": "yamaoka","age": 22}]'
    bucket = 's3-backet-redshift'
    key = 'test_' + datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '.json'
    bucket = s3.Object(bucket,key)
    response = bucket.put(Body=file_contents)
    return response

S3のファイルを読み取る

* バケットポリシーに"Action": "s3:GetObject"を追記する
* 自分は読み取りに少し時間がかかってデフォルトの3秒を超えてTimeoutになったので10秒くらいにしておくと良い

import json
import boto3
from datetime import datetime

s3 = boto3.client('s3')

def lambda_handler(event, context):
    bucket = 's3-backet-redshift'
    key = 'test_2022-04-04-06-11-43.json'
    response = s3.get_object(Bucket=bucket, Key=key)
    body = response['Body'].read()
    return body

S3のファイルを削除する

* バケットポリシーに"s3:DeleteObject"を追記する

s3.delete_object(Bucket=bucket, Key=key)

終わりに

この記事を見るとLambdaにS3バケットに対する読み取り権限を付与するのでもいいっぽい。
(update 2022/5/24)SSAの試験勉強をしているとLambdaにIAMポリシーを適用する方が良いとのこと。

参考文献

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
6