Lambda python for daily AWS Billing alert

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’)

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']:

#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:

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!

AWS | GCP | Terraform | Kubernetes —

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store