Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jupyter-naas
GitHub Repository: jupyter-naas/awesome-notebooks
Path: blob/master/AWS/AWS_Get_cost_forecast.ipynb
2973 views
Kernel: Python 3

AWS.png

AWS - Get cost forecast

Give Feedback | Bug report

Tags: #aws #cloud #ce #operations #snippet

Last update: 2023-11-20 (Created: 2021-09-14)

Description: This notebook utilizes the AWS Cost Explorer to retrieve accurate cost forecasts from an AWS account. By leveraging the Cost Explorer's forecasting capabilities, users can proactively plan and estimate their future AWS costs. Stay ahead of your budget with this notebook's integration of the AWS Cost Explorer, enabling you to make informed decisions and optimize your AWS spending.

Input

Import libraries

import naas from datetime import date try: import boto3 except: !pip install boto3 import boto3 import pandas as pd

Setup variables

Mandatory

  • aws_access_key_id: This variable is used to store the AWS access key ID.

  • aws_secret_access_key: This variable is used to store the AWS secret access key.

  • start_date: This variable is used to store the first date to get the data from.

  • end_date: This variable is used to store the last date to get the data from. It must be the first of a month.

Optional

  • granularity: This variable is used to define cost granularity by date. Granularity can only be MONTHLY, DAILY or HOURLY.

  • file_path: This variable is used to define csv file path to be stored in local with billing details.

# Mandatory aws_access_key_id = naas.secret.get("AWS_ACCESS_KEY_ID") or "YOUR_AWS_ACCESS_KEY_ID" aws_secret_access_key = naas.secret.get("AWS_SECRET_ACCESS_KEY") or "YOUR_AWS_SECRET_ACCESS_KEY" start_date = date.today().isoformat() end_date = "2023-11-30" # Optional granularity = "MONTHLY" file_path = "billing_aws.csv"

Model

Connect to AWS

client = boto3.client( "ce", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, )

Get forecast from AWS

ce_forecast = client.get_cost_forecast( TimePeriod={"Start": start_date, "End": end_date}, Metric="BLENDED_COST", Granularity=granularity, )

Output

Display result

forecast = float(ce_forecast["Total"]["Amount"]) print("Forecast Amount:", round(forecast, 2))