In the realm of public cloud management, controlling costs is paramount. AWS provides robust tools like Cost Explorer and Cost Anomaly Detection to monitor and manage expenses effectively. Automating cost reporting can further streamline this process, ensuring that key stakeholders are kept informed without manual intervention.
Automating AWS Cost Reporting with Lambda and SNS
towardsaws.com
Practice Verified Codes and Commands:
1. Setting Up AWS Lambda for Cost Reporting:
<h1>Create a new Lambda function</h1> aws lambda create-function --function-name CostReportLambda \ --runtime python3.8 --role arn:aws:iam::123456789012:role/lambda-execution-role \ --handler lambda_function.lambda_handler --zip-file fileb://lambda_function.zip
2. Configuring EventBridge to Trigger Lambda:
<h1>Create a new EventBridge rule</h1> aws events put-rule --name "MonthlyCostReport" \ --schedule-expression "cron(0 12 1 * ? *)" --state ENABLED
3. Adding Lambda as a Target for EventBridge:
<h1>Add Lambda as a target for the EventBridge rule</h1> aws events put-targets --rule "MonthlyCostReport" \ --targets "Id"="1","Arn"="arn:aws:lambda:us-east-1:123456789012:function:CostReportLambda"
4. Setting Up SNS for Notifications:
<h1>Create an SNS topic</h1> aws sns create-topic --name CostReportTopic <h1>Subscribe an email to the SNS topic</h1> aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:CostReportTopic \ --protocol email --notification-endpoint [email protected]
5. Lambda Function Code to Send Cost Report:
import boto3 from datetime import datetime, timedelta def lambda_handler(event, context): ce = boto3.client('ce') sns = boto3.client('sns') <h1>Define the time period for the cost report</h1> end_date = datetime.utcnow().date() start_date = (end_date - timedelta(days=30)).strftime('%Y-%m-%d') end_date = end_date.strftime('%Y-%m-%d') <h1>Get the cost and usage data</h1> response = ce.get_cost_and_usage( TimePeriod={'Start': start_date, 'End': end_date}, Granularity='MONTHLY', Metrics=['UnblendedCost'] ) <h1>Format the report</h1> report = f"Cost Report for {start_date} to {end_date}:\n" for result in response['ResultsByTime']: report += f"Start: {result['TimePeriod']['Start']}, End: {result['TimePeriod']['End']}, Cost: {result['Total']['UnblendedCost']['Amount']} {result['Total']['UnblendedCost']['Unit']}\n" <h1>Publish the report to SNS</h1> sns.publish( TopicArn='arn:aws:sns:us-east-1:123456789012:CostReportTopic', Message=report, Subject='Monthly AWS Cost Report' ) return { 'statusCode': 200, 'body': 'Cost report sent successfully' }
What Undercode Say:
In the ever-evolving landscape of cloud computing, managing costs efficiently is not just a best practice but a necessity. AWS offers a suite of tools designed to help users keep their cloud expenses in check. Cost Explorer and Cost Anomaly Detection are indispensable for monitoring and identifying unexpected costs. Automating the process of generating and distributing cost reports using AWS Lambda, EventBridge, and SNS not only saves time but also ensures that stakeholders are always in the loop.
The provided code snippets and commands demonstrate how to set up an automated cost reporting system. By leveraging AWS Lambda, you can create a function that fetches cost data, formats it into a readable report, and sends it via SNS to designated recipients. EventBridge can be used to trigger this Lambda function on a schedule, ensuring that reports are generated and sent consistently without manual intervention.
Additionally, the use of SNS allows for flexible notification mechanisms, enabling reports to be sent via email, SMS, or other supported protocols. This setup is highly customizable and can be adapted to fit the specific needs of any organization.
In conclusion, automating AWS cost reporting is a powerful way to maintain financial control over your cloud resources. By utilizing AWS’s native services like Lambda, EventBridge, and SNS, you can create a robust, automated system that keeps your team informed and your costs under control. This approach not only enhances operational efficiency but also provides peace of mind, knowing that your cloud expenses are being monitored and managed proactively.
For further reading and more detailed instructions, you can refer to the original article on towardsaws.com.
References:
Hackers Feeds, Undercode AI