LoginSignup
1
0

More than 5 years have passed since last update.

Amazon S3のリダイレクトルールを手軽に更新できるようにする

Last updated at Posted at 2017-09-22

始めに

この記事の続きです。
なんでこんなことをしてしまったのかはこの記事を読んでください。

やりたいこと

Amazon S3のリダイレクトルールに新しいルールを追加したい。
でもリダイレクトルールいちいち編集して保存したくない。
そもそもMFAが面倒なのでリダイレクトルールを追加するためだけに毎回AWSコンソールを開きたくない。

やったこと

  • Amazon S3の新しいリダイレクトルールを、AWS CLI一行で更新できるようにした
    • リダイレクトルールはDynamoDBに保存する
    • リダイレクトルールは、DynamoDBの更新をトリガーにしてAWS Lambdaが自動で更新する

構築手順

DynamoDB

任意のテーブル名で作ってください。
前の記事にリダイレクトルールの完成形があります、これに必要な属性を定義します。

  • url
  • host
  • name

デフォルトページを先に定義しておきましょう。

  • {"url":"twitter.com"}
  • {"host":"you"}
  • {"name":"default"}

AWS Lambda

Python3.6で書きます。

#! /user/local/bin/python
# -*- coding:utf-8 -*-
import boto3
from boto3.dynamodb.conditions import Attr

def lambda_handler(event, context):
    # init
    table = boto3.resource('dynamodb').Table('任意のテーブル名')
    # scan table
    res = table.scan(FilterExpression=Attr('url').begins_with('clouddrive'))
    row_def = table.scan(FilterExpression=Attr('name').eq('default'))['Items'][0]
    # template
    conf = {"IndexDocument": {"Suffix": "tekitou"}, "RoutingRules":[]}
    # add routing rules
    for row in res['Items']:
        conf['RoutingRules'].append({"Condition": {"KeyPrefixEquals": row['name']},"Redirect": {"HostName" : row['host'],"ReplaceKeyWith" : row['url']}})
    # add default rule
    conf['RoutingRules'].append({"Redirect":{"HostName" : row_def['host'],"ReplaceKeyWith" : row_def['url']}})
    # put routing rules
    s3client = boto3.client('s3')
    s3client.put_bucket_website(Bucket='任意のBucket',WebsiteConfiguration=conf)

    return 'ok'

必要なロールは

  • "dynamodb:GetItem"
  • "dynamodb:Scan"
  • "s3:GetBucketWebsite"
  • "s3:PutBucketWebsite"

とAWSLambdaDynamoDBExecutionRole(AWS 管理ポリシー)なので作ったLambdaさんにつけてあげてください。

Lambdaのトリガーは、先ほど作ったDynamoDBの任意のテーブルを選択してください。
これで、AWS CLIからレコードを追加したらあとはLambdaさんが頑張ってくれます。

IAM

AWS CLIからDynamoDBにレコードを追加するので、DynamoDBに書き込み権限のあるIAMユーザを作成してアクセスキーを取得してお使いのPCのawsコマンドに設定しておきます。

最後に

ローカルで

aws dynamodb put-item --table-name 任意のテーブル名 --item '{"host": {"S":"www.amazon.co.jp"},"name": {"S":"comiket_20170813"},"url": {"S":"clouddrive/share/aaabbbccc"}}'

を叩いたら、新しいルーティングが設定されます。

おわり

簡単でしたね。(吐血)
DynamoDBとか、あまり詳しくなかったので良い勉強になりました。boto3.dynamodbのドキュメント・サンプルの少なさよ

おことわり

今回実装したのはルーティングの追加のみです。
使わなくなったルーティングの削除の実装は読者の課題としようと思います。

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