0
0

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.

S3ファイルをまとめてダウンロードできる環境をテストイベントの設定を利用して作る

Last updated at Posted at 2017-12-05

S3ファイルをまとめてダウンロードできる環境を作る の続きになります。

追加仕様

設定情報をLambda内ではなくテストイベントに保存する。
そうすることでコードを修正することなく何パターンも設定を作ることができる。

テストイベントの作成

  1. テストイベントの設定
  2. 新しいテストイベントの作成
  3. イベント名は適当にわかりやすい名前にする
  4. テストコードとPythonコードを修正する
json
{
  "s3": {
    "in": {
      "bucket": "s3inbucket",
      "prefix": "hoge/neko/",
      "extension": ".jpg",
      "max": 1000,
      "marker": ""
    },
    "out": {
      "bucket": "s3outbucket",
      "dir": "out/",
      "filenmae": "archive"
    }
  }
}

Pythonコード

lambda_function.py
import boto3
import tarfile
import os

s3_client = boto3.client('s3')


def lambda_handler(event, context):
    response = s3_client.list_objects(Bucket=event['s3']['in']['bucket'], Prefix=event['s3']['in']['prefix'], MaxKeys=event['s3']['in']['max'], Marker=event['s3']['in']['marker'])
    if 'Contents' not in response:
        return

    s3_files = [c['Key'] for c in response['Contents'] if c['Key'].endswith(event['s3']['in']['extension'])]

    if s3_files:
        get_s3_files(event, s3_files)
        create_archive(event)
        return s3_files


def get_s3_files(event, s3_files):
    for s3_file in s3_files:
        basename = os.path.basename(s3_file)
        tmp_file = os.path.join('/tmp/', basename)
        s3_client.download_file(event['s3']['in']['bucket'], s3_file, tmp_file)


def create_archive(event):
    out_file = os.path.join(event['s3']['out']['dir'], event['s3']['out']['filenmae'] + '.tar.gz')
    archive_file = os.path.join('/tmp/', event['s3']['out']['filenmae'] + '.tar.gz')

    archive = tarfile.open(archive_file, mode='w:gz')
    archive.add('/tmp/', arcname=event['s3']['out']['filenmae'])
    archive.close()

    s3_client.upload_file(archive_file, event['s3']['out']['bucket'], out_file)
    print('output ' + event['s3']['out']['bucket'] + ':' + out_file)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?