実行ロールには、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!')
}