Skip to content

Instantly share code, notes, and snippets.

@jitsejan
Created March 25, 2021 01:21
Show Gist options
  • Save jitsejan/05e72e47bde4a00063becdac38b22bb7 to your computer and use it in GitHub Desktop.
Save jitsejan/05e72e47bde4a00063becdac38b22bb7 to your computer and use it in GitHub Desktop.
Simple script that can assume the role after providing the MFA token
from datetime import datetime, timedelta
import boto3
ACCOUNT_NUMBER = 1234567890
MAX_DURATION = 129600
NUM_DAYS = 30
USER = "jitsejan"
# Prompt user for the MFA token
token = input("MFA token: ")
# Get the credentials to assume the role
session = boto3.session.Session(profile_name="jjmain")
sts_client = session.client("sts")
assumed_role_object = sts_client.get_session_token(
DurationSeconds=MAX_DURATION,
SerialNumber=f"arn:aws:iam::{ACCOUNT_NUMBER}:mfa/{USER}",
TokenCode=token,
)
credentials = assumed_role_object["Credentials"]
# Setup the Cost Explorer client
ce_client = session.client(
"ce",
aws_access_key_id=credentials["AccessKeyId"],
aws_secret_access_key=credentials["SecretAccessKey"],
aws_session_token=credentials["SessionToken"],
)
# Get the cost and usage for the provided time period
now = datetime.utcnow().now()
start = (now - timedelta(days=NUM_DAYS)).strftime("%Y-%m-%d")
end = now.strftime("%Y-%m-%d")
data = ce_client.get_cost_and_usage(
TimePeriod={"Start": start, "End": end},
Granularity="MONTHLY",
Metrics=["UnblendedCost"],
)
# Get the total unblended cost
total_cost = 0
for timeperiod in data["ResultsByTime"]:
total_cost += float((timeperiod["Total"]["UnblendedCost"]["Amount"]))
print(f"Total unblended cost in the past {NUM_DAYS} days is {total_cost:.2f} USD")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment