CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pulumi--aws

A Pulumi package for creating and managing Amazon Web Services (AWS) cloud resources with infrastructure-as-code.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

cost.mddocs/services/

Cost Management Services

AWS services for cost monitoring, budgeting, and optimization.

Services Overview

Cost Explorer - Cost and Usage Analytics

Visualize, understand, and manage your AWS costs and usage over time.

import { costexplorer } from "@pulumi/aws";

// Create a cost anomaly monitor
const anomalyMonitor = new costexplorer.AnomalyMonitor("spending-monitor", {
    name: "unusual-spending",
    monitorType: "DIMENSIONAL",
    monitorDimension: "SERVICE",
});

// Create a subscription for anomaly alerts
new costexplorer.AnomalySubscription("cost-alerts", {
    name: "cost-anomaly-alerts",
    threshold: 100, // Alert when anomaly exceeds $100
    frequency: "DAILY",
    monitorArnLists: [anomalyMonitor.arn],
    subscribers: [
        {
            type: "EMAIL",
            address: "finance@example.com",
        },
        {
            type: "SNS",
            address: costAlertTopic.arn,
        },
    ],
});

// Create a cost category for resource organization
const costCategory = new costexplorer.CostCategory("departments", {
    name: "Departments",
    ruleVersion: "CostCategoryExpression.v1",
    rules: [
        {
            value: "Engineering",
            rule: {
                tags: {
                    key: "Department",
                    values: ["Engineering", "Development"],
                },
            },
        },
        {
            value: "Marketing",
            rule: {
                tags: {
                    key: "Department",
                    values: ["Marketing", "Sales"],
                },
            },
        },
    ],
    defaultValue: "Other",
});

// Enable cost allocation tags
new costexplorer.CostAllocationTag("project-tag", {
    tagKey: "Project",
    status: "Active",
});

Key Resources: AnomalyMonitor, AnomalySubscription, CostCategory, CostAllocationTag

Data Sources: getCostCategory, getTags

Use Cases: Cost analysis, anomaly detection, cost attribution, trend analysis, forecasting

Details

Features:

  • Cost and usage reporting
  • Forecasting
  • Rightsizing recommendations
  • Reservation recommendations
  • Savings Plans recommendations
  • Cost anomaly detection

Budgets - Cost and Usage Budgets

Set custom budgets and receive alerts when costs or usage exceed thresholds.

import { budgets } from "@pulumi/aws";

// Create a monthly cost budget
const monthlyBudget = new budgets.Budget("monthly-spend", {
    name: "monthly-budget",
    budgetType: "COST",
    limitAmount: "10000",
    limitUnit: "USD",
    timeUnit: "MONTHLY",
    notifications: [
        {
            comparisonOperator: "GREATER_THAN",
            threshold: 80,
            thresholdType: "PERCENTAGE",
            notificationType: "ACTUAL",
            subscriberEmailAddresses: ["finance@example.com"],
        },
        {
            comparisonOperator: "GREATER_THAN",
            threshold: 100,
            thresholdType: "PERCENTAGE",
            notificationType: "ACTUAL",
            subscriberEmailAddresses: ["cto@example.com"],
            subscriberSnsTopicArns: [criticalAlertTopic.arn],
        },
        {
            comparisonOperator: "GREATER_THAN",
            threshold: 90,
            thresholdType: "PERCENTAGE",
            notificationType: "FORECASTED",
            subscriberEmailAddresses: ["finance@example.com"],
        },
    ],
});

// Create a budget for specific services
const ec2Budget = new budgets.Budget("ec2-spend", {
    name: "ec2-monthly-budget",
    budgetType: "COST",
    limitAmount: "5000",
    limitUnit: "USD",
    timeUnit: "MONTHLY",
    costFilters: {
        Service: ["Amazon Elastic Compute Cloud - Compute"],
    },
    notifications: [{
        comparisonOperator: "GREATER_THAN",
        threshold: 80,
        thresholdType: "PERCENTAGE",
        notificationType: "ACTUAL",
        subscriberEmailAddresses: ["devops@example.com"],
    }],
});

// Create a usage budget for EC2 hours
const ec2UsageBudget = new budgets.Budget("ec2-usage", {
    name: "ec2-hours-budget",
    budgetType: "USAGE",
    limitAmount: "10000",
    limitUnit: "HOURS",
    timeUnit: "MONTHLY",
    costFilters: {
        Service: ["Amazon Elastic Compute Cloud - Compute"],
    },
    notifications: [{
        comparisonOperator: "GREATER_THAN",
        threshold: 75,
        thresholdType: "PERCENTAGE",
        notificationType: "ACTUAL",
        subscriberEmailAddresses: ["devops@example.com"],
    }],
});

// Create a budget action to automatically stop instances
const budgetAction = new budgets.BudgetAction("stop-dev-instances", {
    budgetName: monthlyBudget.name,
    actionType: "APPLY_IAM_POLICY",
    approvalModel: "AUTOMATIC",
    notificationType: "ACTUAL",
    actionThreshold: {
        actionThresholdType: "PERCENTAGE",
        actionThresholdValue: 95,
    },
    definition: {
        iamActionDefinition: {
            policyArn: denyEC2Policy.arn,
            roles: [devRole.arn],
        },
    },
    subscribers: [{
        subscriptionType: "EMAIL",
        address: "devops@example.com",
    }],
    executionRoleArn: budgetActionRole.arn,
});

Key Resources: Budget, BudgetAction

Use Cases: Cost control, spending alerts, budget tracking, automated cost controls, departmental budgets

Details

Budget Types:

  • Cost budgets
  • Usage budgets
  • Reservation utilization budgets
  • Reservation coverage budgets
  • Savings Plans utilization budgets
  • Savings Plans coverage budgets

Cost Optimization Hub - Optimization Recommendations

Centralized hub for cost optimization recommendations across your AWS environment.

import { costoptimizationhub } from "@pulumi/aws";

// Enable the Cost Optimization Hub
const preferences = new costoptimizationhub.EnrollmentStatus("enable-hub", {
    status: "ACTIVE",
});

Key Resources: EnrollmentStatus, Preferences

Use Cases: Rightsizing recommendations, idle resource detection, savings opportunities, cost optimization tracking

Details

Recommendation Types:

  • EC2 rightsizing
  • EBS volume optimization
  • Idle resource deletion
  • Reserved Instance purchases
  • Savings Plans purchases
  • Lambda optimization

Cost and Usage Report (CUR) - Detailed Billing Reports

Generate comprehensive cost and usage data for detailed analysis.

import { cur } from "@pulumi/aws";

// Create a Cost and Usage Report
const report = new cur.ReportDefinition("detailed-billing", {
    reportName: "hourly-cost-usage",
    timeUnit: "HOURLY",
    format: "Parquet",
    compression: "Parquet",
    additionalSchemaElements: ["RESOURCES"],
    s3Bucket: billingBucket.id,
    s3Prefix: "cur-reports",
    s3Region: region,
    additionalArtifacts: ["ATHENA"],
    refreshClosedReports: true,
    reportVersioning: "OVERWRITE_REPORT",
});

// Query CUR data with Athena
const curDatabase = new aws.athena.Database("cur-data", {
    name: "cur_database",
    bucket: athenaResultsBucket.id,
});

Key Resources: ReportDefinition

Use Cases: Detailed cost analysis, chargeback/showback, custom billing reports, BI integration, programmatic cost analysis

Details

Report Configurations:

  • Time granularity: Hourly, Daily, Monthly
  • Data formats: CSV, Parquet
  • Resource-level details
  • Athena integration
  • QuickSight integration

Billing - Billing Management

Manage billing preferences, payment methods, and access controls.

import { billing } from "@pulumi/aws";

// Create a billing group (for AWS Organizations)
// Note: Billing resources are managed primarily through the AWS Console
// Pulumi support for billing resources is limited

Use Cases: Consolidated billing, billing alarms, payment methods, tax settings, billing access control

Details


Compute Optimizer - Resource Optimization Recommendations

ML-powered recommendations for optimal compute resource sizing.

import { computeoptimizer } from "@pulumi/aws";

// Enable Compute Optimizer
const enrollment = new computeoptimizer.EnrollmentStatus("enable-optimizer", {
    status: "Active",
});

// Configure recommendation preferences
const preferences = new computeoptimizer.RecommendationPreferences("ec2-prefs", {
    resourceType: "Ec2Instance",
    scope: {
        name: "Organization",
    },
    enhancedInfrastructureMetrics: "Active",
    inferredWorkloadTypes: "Active",
    externalMetricsPreference: {
        source: "Datadog",
    },
});

Key Resources: EnrollmentStatus, RecommendationPreferences

Use Cases: EC2 rightsizing, Auto Scaling optimization, Lambda function optimization, EBS volume optimization

Details

Supported Resources:

  • EC2 instances
  • Auto Scaling groups
  • EBS volumes
  • Lambda functions
  • ECS services on Fargate

Cost Optimization Best Practices

Tag Strategy

// Apply consistent tags for cost tracking
const defaultTags = {
    Environment: "production",
    Project: "web-app",
    Department: "Engineering",
    CostCenter: "CC-1234",
    Owner: "team@example.com",
};

// Apply to resources
const instance = new aws.ec2.Instance("web", {
    tags: defaultTags,
    // ... other config
});

Reserved Instances and Savings Plans

// Use Savings Plans for flexible commitment-based savings
// Managed through AWS Console or Cost Explorer

// Tag instances to track RI/Savings Plans coverage
const compute = new aws.ec2.Instance("app", {
    tags: {
        ...defaultTags,
        PricingModel: "OnDemand", // or "Reserved", "SavingsPlan"
    },
});

Right-sizing and Auto Scaling

// Use Auto Scaling for dynamic capacity
const asg = new aws.autoscaling.Group("web", {
    minSize: 2,
    maxSize: 10,
    desiredCapacity: 4,
    targetGroupArns: [targetGroup.arn],

    // Cost-optimized launch template
    mixedInstancesPolicy: {
        instancesDistribution: {
            onDemandBaseCapacity: 0,
            onDemandPercentageAboveBaseCapacity: 20,
            spotAllocationStrategy: "price-capacity-optimized",
        },
        launchTemplate: {
            launchTemplateSpecification: {
                launchTemplateId: template.id,
            },
            overrides: [
                { instanceType: "t3.medium" },
                { instanceType: "t3a.medium" },
                { instanceType: "t2.medium" },
            ],
        },
    },
});

Related Services

  • CloudWatch - Cost monitoring dashboards and alarms
  • SNS - Budget and cost alert notifications
  • Lambda - Automated cost optimization actions
  • S3 - Store Cost and Usage Reports
  • Athena - Query billing data
  • QuickSight - Visualize cost data

For complete service list, see All Services A-Z.

Install with Tessl CLI

npx tessl i tessl/npm-pulumi--aws@7.16.0

docs

index.md

quickstart.md

README.md

tile.json