Skip to content

Instantly share code, notes, and snippets.

@yogeshnile
Last active April 10, 2023 12:54
Show Gist options
  • Save yogeshnile/515df0964d5db824a50a1bfe2f5512e9 to your computer and use it in GitHub Desktop.
Save yogeshnile/515df0964d5db824a50a1bfe2f5512e9 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment