Costos y optimización
6.15.4kata 4 de 5

Budgets y Alertas

Crear presupuestos, alertas de forecast, tags de costo y Cost Explorer

AWS Budgets es el sistema de alerta de costos. Defines un presupuesto (límite de gasto mensual) y AWS te alerta cuando el gasto real o el forecast supera un porcentaje del presupuesto. A diferencia de Cost Explorer (retrospectivo), Budgets es proactivo: alerta antes de que el mes termine. Puedes crear budgets por servicio, por tag, por cuenta, o por familia de instancias.

Los tipos de alerta son: ACTUAL (gasto ya ocurrido supera el umbral) y FORECASTED (proyección del mes actual supera el umbral). El FORECASTED es más útil para prevenir sorpresas: si el 15 del mes ya has gastado el 60% del presupuesto, AWS proyecta que terminarás el mes al 120% y alerta inmediatamente — tienes 2 semanas para corregir.

Los Cost Allocation Tags son el mecanismo para desglosar costos por proyecto, equipo, o entorno. Aplicas tags como `Project=MLPipeline`, `Environment=prod`, `Team=data-engineering` a cada recurso en AWS. En Cost Explorer, agrupas por tag para ver cuánto gasta cada proyecto. Sin tags, solo ves el total por servicio (EC2, S3, Lambda) pero no sabes qué proyecto o equipo es responsable.

Cost Explorer es la herramienta de análisis retrospectivo. Muestra costos por servicio, por tag, por región, por cuenta. Los informes más útiles son: Top 10 services (qué servicio gasta más), Month-over-month change (qué creció más este mes), y Instance type breakdown (qué tipos de instancia son más costosos). Cost Explorer también ofrece recomendaciones de RI y Savings Plans basadas en tu historial.

structure.txt
import boto3
from datetime import datetime

budgets = boto3.client('budgets')
ce = boto3.client('ce')

# === CREATE BUDGET WITH MULTIPLE ALERTS ===
def create_project_budget(account_id: str, project_name: str, monthly_limit_usd: float):
    budgets.create_budget(
        AccountId=account_id,
        Budget={
            'BudgetName': f'{project_name}-monthly',
            'BudgetLimit': {'Amount': str(monthly_limit_usd), 'Unit': 'USD'},
            'TimeUnit': 'MONTHLY',
            'BudgetType': 'COST',
            # Filter to only this project's costs (requires cost allocation tags)
            'CostFilters': {
                'TagKeyValue': [f'user:Project${project_name}']
            }
        },
        NotificationsWithSubscribers=[
            {  # Alert at 70% actual spend
                'Notification': {
                    'NotificationType': 'ACTUAL',
                    'ComparisonOperator': 'GREATER_THAN',
                    'Threshold': 70,
                    'ThresholdType': 'PERCENTAGE'
                },
                'Subscribers': [
                    {'SubscriptionType': 'EMAIL', 'Address': 'team@company.com'}
                ]
            },
            {  # Alert when forecast > 100%
                'Notification': {
                    'NotificationType': 'FORECASTED',
                    'ComparisonOperator': 'GREATER_THAN',
                    'Threshold': 100,
                    'ThresholdType': 'PERCENTAGE'
                },
                'Subscribers': [
                    {'SubscriptionType': 'EMAIL', 'Address': 'ops@company.com'},
                    {'SubscriptionType': 'SNS', 'Address': 'arn:aws:sns:...:cost-alerts'}
                ]
            }
        ]
    )

# === TAG RESOURCES FOR COST ALLOCATION ===
def tag_resources(resource_arns: list[str], project: str, env: str, team: str):
    tagging = boto3.client('resourcegroupstaggingapi')
    tagging.tag_resources(
        ResourceARNList=resource_arns,
        Tags={
            'Project': project,
            'Environment': env,
            'Team': team,
            'ManagedBy': 'terraform'  # or 'cloudformation', 'cdk'
        }
    )

# === ANALYZE COSTS WITH COST EXPLORER ===
def get_top_services_cost(days_back: int = 30) -> list[dict]:
    end = datetime.now().strftime('%Y-%m-%d')
    start = (datetime.now().replace(day=1)).strftime('%Y-%m-%d')  # first of month

    response = ce.get_cost_and_usage(
        TimePeriod={'Start': start, 'End': end},
        Granularity='MONTHLY',
        Metrics=['UnblendedCost'],
        GroupBy=[{'Type': 'DIMENSION', 'Key': 'SERVICE'}]
    )

    results = []
    for group in response['ResultsByTime'][0]['Groups']:
        service = group['Keys'][0]
        cost = float(group['Metrics']['UnblendedCost']['Amount'])
        if cost > 0.01:
            results.append({'service': service, 'cost': cost})

    return sorted(results, key=lambda x: x['cost'], reverse=True)

# Get cost by project tag
def get_cost_by_project() -> list[dict]:
    response = ce.get_cost_and_usage(
        TimePeriod={
            'Start': (datetime.now().replace(day=1)).strftime('%Y-%m-%d'),
            'End': datetime.now().strftime('%Y-%m-%d')
        },
        Granularity='MONTHLY',
        Metrics=['UnblendedCost'],
        GroupBy=[{'Type': 'TAG', 'Key': 'Project'}]  # group by Project tag
    )
    return [
        {'project': g['Keys'][0], 'cost': float(g['Metrics']['UnblendedCost']['Amount'])}
        for period in response['ResultsByTime']
        for g in period['Groups']
    ]

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    # No budget configured # Bill at end of month: $15,000 unexpected # Cause: a Lambda in a loop invoked 100M times # No early warning

  2. 02

    # Resources without cost allocation tags # Cost Explorer shows $5,000 in EC2 but can't break down by project ec2.run_instances( ImageId='ami-xxx', InstanceType='m5.large', # No Tags )

  3. 03

    # Monthly cost review: someone modified costs report # No systematic check, issues discovered too late # No way to identify which project or service spiked