Lambda python for daily AWS Billing alert

Rafael Natali
2 min readMay 30, 2019

It’s excellent all the flexibility and resources that cloud computing provide to us. We can spin up servers, databases, and load balancers in minutes. However, it’s easy to lose track of how much you are spending and at the end of the month together with your bill you receive an unpleasant surprise.

Why wait until the end of the month to verify your spending?

Let’s use Lambda, Python, CloudWatch, and Simple Notification Service (SNS) to alert us daily regarding our billing in AWS.

Firstly, let’s create a Lambda function with permission (role) to access CostExplorer and to publish to SNS.

Using the Boto3 — Cost Explorer client we’ll retrieve the billing information for our account. This piece of code will get yesterday’s total amount spent.

########### Getting the Daily Amount spent in AWS ########### 
# opening connection with cost explorer
billing_client = boto3.client(‘ce’)
# getting dates (yyyy-MM-dd) and converting to string
today = date.today()
yesterday = today — datetime.timedelta(days = 1)
str_today = str(today)
str_yesterday = str(yesterday)
# connecting to cost explorer to get daily aws usage
response = billing_client.get_cost_and_usage(
TimePeriod={
‘Start’: str_yesterday,
‘End’: str_today },
Granularity=’DAILY’,
Metrics=[ ‘UnblendedCost’,]
)

The result of the billing_client.get_cost_and_usage will be a dictionary. Therefore, we need to iterate through it to get the amount. Amount is a string at first, so, we change to a float to use in a comparison later on.

# iteract through the response to get the daily amount
for r in response['ResultsByTime']:
str_amount=(r['Total']['UnblendedCost']['Amount'])

#convert the amount to float
amount = float(str_amount)

Now we have our daily amount. Using a simple if statement we compare with a value that we understand is reasonable for 1 single day and if it’s NOT OK, we send a message to a SNS topic. Please, refer to the AWS documentation if you need to create a topic.

# Sending SNS notification if the amount is higher than expected 

if amount > your_estimation:
# Create an SNS client
sns = boto3.client('sns')

# Publish a warning message to the specified SNS topic
response = sns.publish(
TopicArn='arn:aws:sns:region:account:TopicName',
Message='Yesterday amount spent was above the threshold!'
)

Lastly, we can go to CloudWatch and create a scheduled rule to execute this lambda every day and get notified if something happened the day before.

Start saving!

--

--