3
3

More than 3 years have passed since last update.

Lambda から S3 を使う (Python3)

Last updated at Posted at 2020-03-04

実行ロールには、S3 へのアクセス権がついている必要があります。

バケットの一覧

list_buckets.py
# ------------------------------------------------------------------
import json
import boto3
print('Loading function')
s3 = boto3.resource('s3')

def lambda_handler(event, context):
    print("*** start ***")
#
    it = 1
 #
    for bucket in s3.buckets.all():
        print(str(it) + ':' + bucket.name)
        it +=  1

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

# ------------------------------------------------------------------

バケット内のファイルの一覧

list_files.py
import json
import boto3
print('Loading function')
s3 = boto3.resource('s3')

def lambda_handler(event, context):
    print("*** start ***")
#
    bucket_name = "bucket01"

    my_bucket = s3.Bucket(bucket_name)
    for object in my_bucket.objects.all():
       print(object)
       print(object.key)
#

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

ファイルの作成

s3_put.py

import json
import boto3
print('Loading function')
s3 = boto3.resource('s3')

def lambda_handler(event, context):
    print("*** start ***")

    bucket_name = "bucket01"

    json_key = "sample8.json"
    obj = s3.Object(bucket_name,json_key)

    test_json = {'key': 'valueaaa',
        'key2': 'Hello'}

    data = json.dumps(test_json).encode('utf-8')
    r = obj.put(Body = data)

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
3
3
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
3
3