Unfortunately, AWS doesn’t have an API to get custom billing for a time-frame, if the bill exceeds the set amount you will be charged by the month’s end but this alert can get trigged in a few days and the damage is already done.
I have a template to raise alarms in CloudWatch, and I want to customized to monitor daily and send alerts if the bill exceeds a certain amount:
Description: >
This template deploys the billing stack
Parameters:
pBillingThreshold:
Description: Sets the billing alert to go off above this figure
Type: Number
Default: 60000
AlarmAction:
Description: Monitoring Alarm Action SNS
Type: String
Default: "<put your arn here>"
Resources:
SpendingAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: !Join ['', [Alarm if EC2 spending is over $, !Ref 'pBillingThreshold']]
Namespace: AWS/Billing
MetricName: EstimatedCharges
Dimensions:
- Name: Currency
Value: USD
- Name: ServiceName
Value: AmazonEC2
- Name: LinkedAccount
Value: <put your linkedacount here>
Statistic: Maximum
Period: '21600'
EvaluationPeriods: '1'
Threshold: !Ref 'pBillingThreshold'
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- !Ref AlarmAction
I found a command that might help, but I want to incorporate this in my template, and I am low with the ideas:
aws --region us-east-1 cloudwatch get-metric-statistics
--namespace "AWS/Billing"
--metric-name "EstimatedCharges"
--dimension "Name=Currency,Value=USD"
--start-time $(date +"%Y-%m-%dT%H:%M:00"
--date="-24 hours")
--end-time $(date +"%Y-%m-%dT%H:%M:00" --date="-12 hours")
--statistic Maximum
--period 60
--output text | sort -r -k 3 | head -n 1 | cut -f 2
aws ce get-cost-and-usage --time-period Start=$(date +"%Y-%m-%d" --date="-24 hours"),End=$(date +"%Y-%m-%d") --granularity=DAILY --metrics BlendedCost