内容
AWS利用料をDailyでメール通知するlambda関数です。
設定
- SNS Topic作成
- Lambda用のロール作成
CostExploereへアクセス(ce:GetCostAndUsage)及びSNSのパブリッシュ(sns:Publish)権限 - Lambda関数作成
- EventBridgeからスケジュール設定
コード
import boto3
import datetime
# SNS Topic
topicArn = 'arn:aws:sns:ap-northeast-1:"account_id":"topic_name"'
# 1 days ago
date1 = (datetime.datetime.now() - datetime.timedelta(days = 1)).strftime('%Y-%m-%d')
# 2 days ago
date2 = (datetime.datetime.now() - datetime.timedelta(days = 2)).strftime('%Y-%m-%d')
def lambda_handler(event, context):
### Get Daily Cost from Cost Exploere ###
date2 = (datetime.datetime.now() - datetime.timedelta(days = 2)).strftime('%Y-%m-%d')
client = boto3.client('ce', region_name = 'ap-northeast-1')
response = client.get_cost_and_usage(
TimePeriod = {
'Start': date2,
'End': date1
},
Granularity = 'DAILY',
Metrics = [
'UnblendedCost',
]
)
for ResultsByTime in response['ResultsByTime']:
cost_start = ResultsByTime['TimePeriod']['Start']
cost_end = ResultsByTime['TimePeriod']['End']
cost_amount = ResultsByTime['Total']['UnblendedCost']['Amount']
cost_unit = ResultsByTime['Total']['UnblendedCost']['Unit']
### Send E-mail with SNS ###
client2 = boto3.client('sns')
response2 = client2.publish(
TopicArn = topicArn,
Message = "Cost Start Day:" + cost_start + '\n' + "Cost End Day:" + cost_end+ '\n' + "Cost:" + cost_amount + '\n' + "Unit:" + cost_unit,
Subject = "AWS Daily Cost Report of Test Environment",
)
return response2