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 1 year has passed since last update.

AWS RDSのインスタンス追加時にクラスターのタグを引継ぐ

Posted at

TODO

  • コンソール上、急ぎリーダーを追加すると、タグ登録漏れに気付かない。
  • 別途タグ未登録監視をしているが、できれば監視を減らしたい。

対策

  • LambdaでRDSのCreateイベントを拾い、タグ登録する

Lambda

lambda_handler Python3.9
import json
import boto3
from botocore import response

def lambda_handler(event, context):
    tagkey = "project" #必須タグ
    dBClusterIdentifier = event["detail"]["responseElements"]["dBClusterIdentifier"]
    dBInstanceArn = event["detail"]["responseElements"]["dBInstanceArn"]

    client = boto3.client('rds')
    response = client.describe_db_clusters(
        DBClusterIdentifier = dBClusterIdentifier
    )
    
    dBClusterArn = response['DBClusters'][0]['DBClusterArn']
    clst_tags = client.list_tags_for_resource(ResourceName = dBClusterArn)
    clst_tag_list = clst_tags['TagList']

    clst_tag = next(iter(filter(lambda tag: tag['Key'] == tagkey, clst_tag_list)), None)
    tagvalue = clst_tag['Value']

    instance_tags = client.list_tags_for_resource(ResourceName = dBInstanceArn)
    tag_list = instance_tags['TagList']
    tag = next(iter(filter(lambda tag: tag['Key'] == tagkey and (tag['Value'] is not None and tag['Value'] != ''), tag_list)), None)
    
    # すでに登録済みはスルー
    if tag is not None:
        print('The tag is already registered.')
        return

    response = client.add_tags_to_resource(
        ResourceName = dBInstanceArn,
        Tags=[{
            'Key': tagkey,
            'Value': tagvalue
        }]
    )
    print(response)

    return {
        'statusCode': 200,
        'body': json.dumps('done')
    }

EventBridge (CloudWatch Events)

name: rds-create-instance
Service principal: events.amazonaws.com
url: events/home#/rules/rds-create-instance
イベントバス: default
イベントパターン:
{
  "source": [
    "aws.rds"
  ],
  "detail-type": [
    "AWS API Call via CloudTrail"
  ],
  "detail": {
    "eventSource": [
      "rds.amazonaws.com"
    ],
    "eventName": [
      "CreateDBInstance",
      "CreateDBInstanceReadReplica"
    ]
  }
}

参考

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?