Get AWS Pricing Alerts on Slack

By, Yogesh Nile, DevOps at IAMOPS

 

Monitor your AWS account daily base pricing on your slack account or any other account.

AWS is a great service provider (tool) for businesses as well as individuals. But one major cron of AWS is that “If you do not care about your account then AWS will not care about your pocket”. That is why we need to track the daily base cost of our AWS account.

Here’s how to get your AWS account daily base cost on your slack account practically:

AWS provides the python library to automate your tasks so, you can use that library to track the AWS cost.

As per the diagram below, you can make lambda to get the cost details from cost explorer and send them to slack.

What is Lambda?

AWS Lambda is a serverless compute service that lets you run the code without provisioning or managing servers, creating workload-aware cluster scaling logic, maintaining event integrations, or managing runtimes.

Step 1

  • Create the lambda function in any particular region (where you want).
  • Increase lambda timeout to 1 minute.
  • Lambda requires to access cost explorer read-only access so that you can add the cost explorer read-only policy to lambda IAM Role. AWS does not provide cost explorer read-only policy so, we need to create a custom policy.
  • Attach the below custom policy in lambda role.
				
					{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ce:GetCostAndUsageWithResources",
                "ce:GetCostAndUsage"
            ],
            "Resource": "*"
        }
    ]
}
				
			

Step 2

  • Lambda requires the external python library to run the code. You can download the external library from this link and attach it to the lambda layer.
  • Copy the below python code in your Lambda function.
				
					import json
import boto3
import requests
from datetime import datetime, timedelta

CLIENT = boto3.client('ce')

SLACK_WEBHOOK_URL = '' # Enter the slack webhook url.

def lambda_handler(event, context):
    START_DATE = (datetime.now() - timedelta(days=2)).strftime('%Y-%m-%d')
    END_DATE = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
    
    AWS_ACCOUNT_ID = [''] # Enter your aws account id. If you have multiple accounts put all account ids.
    
    for account_id in AWS_ACCOUNT_ID:
        COST = CLIENT.get_cost_and_usage(
            TimePeriod = {'Start': START_DATE, 'End': END_DATE},
            Granularity = 'DAILY',
            Metrics = ['UnblendedCost'],
            Filter = {'Dimensions': {
                'Key': 'LINKED_ACCOUNT', 'Values': [account_id]
            }}
        )
        
        TOTAL_COST = round(float(COST['ResultsByTime'][0]['Total']['UnblendedCost']['Amount']), 2)
        UNIT = COST['ResultsByTime'][0]['Total']['UnblendedCost']['Unit']
        
        SLACK_MESSAGE = {
            "channel": "#aws-cost",
            "username": "AWS Cost Monitor",
            "text": f"Your AWS account {account_id} due {TOTAL_COST} {UNIT} on {START_DATE}.",
            "icon_emoji": ":ghost:",
        }
        ENCODED_SLACK_MESSAGE = json.dumps(SLACK_MESSAGE).encode('utf-8')
        
        SLACK_RESPONSE = requests.post(SLACK_WEBHOOK_URL, ENCODED_SLACK_MESSAGE)
        print(SLACK_RESPONSE.text)
				
			
  • Change to two-part in the above code.
  1. Enter the slack webhook URL in line no. 8
  2. Enter the AWS account ID in line no. 14. (If you have multiple accounts then insert all account numbers in the list but make sure all accounts are registered in one organization, and lambda should be in the organization’s root account. Otherwise, insert only current account ID.)

Step 3

  • Now the final step is scheduling the Lambda every day. So, let’s do it.
  • To schedule the lambda we need to create EventBridge and point to the Lambda function.
  • Go to EventBridge console and create the rule for the lambda.
  • Create the corn job by clicking the Schedule tab. Corn job should be as a below image.
  • This cron job will trigger the Lambda every day at 3 AM UTC time.
  • Select Lambda as a target and click create button.
  • After creating rule, refresh the lambda and then the EventBridge rule will be available in the trigger place.

Now you will be able to receive notifications on your slack account.

And that’s it, You just completed the AWS cost monitor on slack.

Apply to

Get AWS Pricing Alerts on Slack

Thanks for applying!

Your application has been sent to our recruitment team successfully. If your profile is selected, our recruitment team will get in touch with you.

We wish you all the best!