1
1

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.

AWS S3の設定情報をlambda(python + boto3)で取得した時のメモ

Last updated at Posted at 2019-03-14

はじめに

AWS S3 の設計書を作ることになり、画面見ながら設定値をコピペしていたら意識が無になって挫折したので、lambdaで取得したjsonを設計書ということにしました

公式資料ではどれがどの設定かわかりづらいし、qiitaにも無いっぽいので自分でので1つ1つ調べました
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#client

本文

設定情報取得に利用したメソッドリスト

引数は全てバケット名になります

import boto3
client = boto3.client('s3')
client.method(
    Backet='backet_name'
)
メソッド名 画面の該当箇所
get_bucket_versioning() プロパティ > バージョニング
get_bucket_logging() プロパティ > サーバーアクセスのログ記録
get_bucket_website() プロパティ > Static website hosting
get_bucket_location() プロパティ > オブジェクトレベルのログ記録
get_bucket_encryption() プロパティ > デフォルト暗号化
get_object_lock_configuration() プロパティ > オブジェクトのロック
get_bucket_tagging() プロパティ > Tags
get_bucket_accelerate_configuration() プロパティ > Transfer acceleration
get_bucket_notification_configuration() プロパティ > Events
get_bucket_request_payment() プロパティ > リクエスタ支払い
get_public_access_block() アクセス権限 > パブリックアクセス設定
get_bucket_acl() アクセス権限 > アクセスコントロールリスト
get_bucket_policy() アクセス権限 > バケットポリシー
get_bucket_cors() アクセス権限 > CORS の設定
get_bucket_lifecycle_configuration() 管理 > ライフサイクル
get_bucket_replication() 管理 > レプリケーション
list_bucket_analytics_configurations() 管理 > 分析
list_bucket_metrics_configurations() 管理 > メトリクス
list_bucket_inventory_configurations() 管理 > インベントリ

※概要は普通のファイルやフォルダなので、他を参考してください。

コード

ココ
show-S3-setting.py

# S3の設計書用の設定情報取得lambda
# bucketごとに情報を設定する

import json
import boto3
from datetime import date, datetime, timedelta

def lambda_handler(event, context):

    client = boto3.client('s3')
    #設定情報を取得するバケットリストを取得
    buckets = client.list_buckets()

    # 設定情報を代入するjson
    json_buckets_setting = {}
    json_buckets_setting['Owner'] = buckets['Owner']
    json_buckets_setting['Buckets'] = []

    for bucket in buckets['Buckets']:
        setting_info = {}

        # 引数が全てBucketなのでevalでメソッドを実行する
        client_methods = [
            'get_bucket_accelerate_configuration', 'get_bucket_acl', 'get_bucket_cors', 'get_bucket_encryption', 'get_bucket_lifecycle_configuration', 'get_bucket_location', 'get_bucket_logging', 'get_bucket_notification_configuration', 'get_bucket_policy_status', 'get_bucket_request_payment', 'get_bucket_tagging', 'get_bucket_versioning', 'get_bucket_website', 'get_object_lock_configuration', 'get_public_access_block', 'list_bucket_analytics_configurations', 'list_bucket_inventory_configurations', 'list_bucket_metrics_configurations'
        ]
        for method_name in client_methods:
            response = None
            try:
                response = eval("client." + method_name)(
                    Bucket=bucket['Name']
                )
            except:
                pass
            setting_info[method_name] = response

        #メソッド毎に設定値を代入
        bucket["s3_setting"] = setting_info
        json_buckets_setting['Buckets'].append(bucket)

    return json.dumps(json_buckets_setting, default=json_serial)

# 日付タイプの変換
def json_serial(obj):
    if isinstance(obj, (datetime, date)):
        # 時差の修正9時間
        obj = obj - timedelta(hours=-9)
        return obj.strftime('%Y/%m/%d %H:%M')
    raise TypeError("Type %s not serializable" % type(obj))

おわりに

これで設計書の最新化がとても楽になりました:relaxed:
あと同じS3作るのもこの値とboto3のメソッド使って作れるはず・・・

下記もできたらやりたい予定
cloudfrontの設定情報をlambda(python + boto3)で取得した時のメモ
lambda の設定情報をlambda(python + boto3)で取得した時のメモ
API Gateway の設定情報をlambda(python + boto3)で取得した時のメモ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?