今回行ったこと
以前、cloudwatchからデータをひっぱり、boto3でawsの料金を毎朝9時に送られるようにしました。 今回はCostExplorerからデータをひっぱり、boto3で毎朝朝9時に前日の料金をメールに送られるようにしました 前回と似通ったところは省きます。
Lambdaの設定
カスタムロールの作成
今回は”sns”,”ce”を使います。下記をコピペしてください。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"aws-portal:*Billing",
"aws-portal:*Usage",
"aws-portal:*PaymentMethods"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "ce:*",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "sns:*",
"Resource": "*"
}
]
}
関数の作成を押した後、このようになるはずです。

スクリプトを書く
TimePeriodの形式は string 型で ”年4桁-月2桁-日2桁” といった形でなければならないので注意が必要です。下記にスクリプトを載せます
import boto3
from datetime import datetime,timedelta
from pprint import pprint
import re
def lambda_handler(event,context):
topic_arn = "*****************************************:"
region1 = "ap-northeast-1"
region2 = "us-east-1"
client = boto3.client(
'ce',
region_name = region2
)
sns = boto3.resource(
"sns",
region_name=region1
)
year = datetime.now().year
month = datetime.now().strftime('%m')
day1 = datetime.now().strftime('%d')
day2 = datetime.now() - timedelta(days=1)
day3 = day2.strftime('%d')
end = str(year) + "-" + str(month) + "-" + str(day1)
start = str(year) + "-" + str(month) + "-" + str(day3)
print(start)
print(end)
response = client.get_cost_and_usage(
TimePeriod={
'Start': start,
'End' : end,
},
Granularity='DAILY',
Metrics= [
'UnblendedCost'
]
)
pprint(response)
answer = re.findall('[0-9]+.[0-9]+',str(response))
ans = answer[2]
mail = sns.Topic(topic_arn).publish(
Message=str(ans) + "$\n\n\n" + "******************",
Subject="payment"
)
return ans
トリガーは以前のものを使用し、完成です。


