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"
]
}
}