Docs

Add an AWS budget alert

This extension adds an AWS budget alert, a resource type Alien doesn't have. The budget emails you when the account's monthly cost passes 80% of a limit. It is a small custom resource, with template parts for CloudFormation and Terraform and no controller.

alien init extensions/budget-alert budget

What you build:

  • A BudgetAlert resource type you add to alien.ts like any Alien resource.
  • A CloudFormation emitter that writes an AWS::Budgets::Budget, and a Terraform emitter that writes an aws_budgets_budget.
  • An importer that records the budget's name after the customer's admin applies the template.

Source: examples/extensions/budget-alert.

In your stack

alien extensions build generates the BudgetAlert builder from the Rust type:

alien.ts
import * as alien from "@alienplatform/core"
import budget, { BudgetAlert } from "./budget/generated"

const alert = new BudgetAlert("costs")
  .monthlyLimitUsd(500)
  .email("cloud-costs@acme.dev")
  .build()

export default new alien.Stack("my-app")
  .extensions([budget])
  .add(alert, "frozen")
  .build()

AWS budgets track the whole account's cost, so the alert covers everything in the account your customer sets up the stack in.

Setup paths

A custom resource works on the setup paths it has a part for. This one works with the CloudFormation and Terraform packages on AWS:

Setup pathWorksWhy
CloudFormation package on AWSYesThe CloudFormation emitter
Terraform package on AWSYesThe Terraform emitter
The setup CLI, Helm, Google Cloud, AzureNoNo controller, no Helm emitter, and no emitters for those clouds

A setup path the resource doesn't support is turned off for every stack that uses it, and alien release says why. With no controller, the resource is frozen only. The customer's admin creates it at initial setup, and a change to it means rerunning initial setup.

The type

The type is a Rust struct. #[alien_resource] registers it as budget/alert, frozen only:

budget/types/src/lib.rs
/// An AWS budget that emails when actual monthly cost passes 80% of the limit.
#[alien_resource(type = "budget/alert", outputs = BudgetAlertOutputs, lifecycles = [Frozen], holds_data = false)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, utoipa::ToSchema, bon::Builder)]
#[serde(rename_all = "camelCase")]
#[builder(start_fn = new)]
pub struct BudgetAlert {
    #[builder(start_fn)]
    pub id: String,
    /// The monthly limit, in US dollars.
    pub monthly_limit_usd: u32,
    /// Who gets the alert.
    pub email: String,
}

/// What Alien records after initial setup.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct BudgetAlertOutputs {
    pub budget_name: String,
}

The CloudFormation emitter

An emitter writes the resource's part of the setup template. It uses the same CfEmitter trait and helpers as Alien's own resources:

budget/hooks/src/lib.rs
pub struct CloudFormation;

impl CfEmitter for CloudFormation {
    fn emit_resources(&self, ctx: &EmitContext<'_>) -> Result<Vec<CfResource>> {
        let alert = resource_config::<BudgetAlert>(ctx, BudgetAlert::RESOURCE_TYPE)?;
        let mut budget = CfResource::new(required_logical_id(ctx)?.to_string(), "AWS::Budgets::Budget".into());
        budget.properties.insert("Budget".into(), CfExpression::object([
            ("BudgetName", stack_name(&alert.id)),
            ("BudgetType", CfExpression::String("COST".into())),
            ("TimeUnit", CfExpression::String("MONTHLY".into())),
            ("BudgetLimit", cf_from_json(json!({ "Amount": alert.monthly_limit_usd, "Unit": "USD" }))?),
        ]));
        budget.properties.insert("NotificationsWithSubscribers".into(), cf_from_json(json!([{
            "Notification": {
                "NotificationType": "ACTUAL",
                "ComparisonOperator": "GREATER_THAN",
                "Threshold": 80,
                "ThresholdType": "PERCENTAGE",
            },
            "Subscribers": [{ "SubscriptionType": "EMAIL", "Address": alert.email }],
        }]))?);
        Ok(vec![budget])
    }

    /// What the importer reads after initial setup. Ref on a budget is its name.
    fn emit_import_ref(&self, ctx: &EmitContext<'_>) -> Result<CfExpression> {
        Ok(CfExpression::object([("budgetName", CfExpression::ref_(required_logical_id(ctx)?))]))
    }
}

stack_name prefixes the budget's name with the CloudFormation stack's name. A budget name must be unique in its account, so two deployments in one account don't collide.

The Terraform emitter

budget/hooks/src/lib.rs
pub struct Terraform;

impl TfEmitter for Terraform {
    fn emit(&self, ctx: &EmitContext<'_>) -> Result<TfFragment> {
        let alert = downcast::<BudgetAlert>(ctx, BudgetAlert::RESOURCE_TYPE)?;
        let label = required_label(ctx)?;
        Ok(TfFragment::default().with_resource(resource_block("aws_budgets_budget", label, [
            attr("name", resource_prefix_template(&alert.id)),
            attr("budget_type", Expression::String("COST".into())),
            attr("time_unit", Expression::String("MONTHLY".into())),
            attr("limit_amount", Expression::String(alert.monthly_limit_usd.to_string())),
            attr("limit_unit", Expression::String("USD".into())),
            nested(block("notification", [
                attr("notification_type", Expression::String("ACTUAL".into())),
                attr("comparison_operator", Expression::String("GREATER_THAN".into())),
                attr("threshold", Expression::Number(80.into())),
                attr("threshold_type", Expression::String("PERCENTAGE".into())),
                attr("subscriber_email_addresses", Expression::Array(vec![Expression::String(alert.email.clone())])),
            ])),
        ])))
    }

    fn emit_import_ref(&self, ctx: &EmitContext<'_>) -> Result<Expression> {
        let label = required_label(ctx)?;
        Ok(expr::object([("budgetName", expr::traversal(["aws_budgets_budget", label, "name"]))]))
    }
}

The importer

After the admin applies the template, Alien reads the template's outputs and runs the resource's importer to record the resource. A frozen-only type needs an importer for each platform it supports, or the deployment is refused at preflight.

budget/hooks/src/lib.rs
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BudgetImport {
    pub budget_name: String,
}

pub struct Importer;

impl ResourceImporter for Importer {
    type ImportData = BudgetImport;

    fn import(&self, data: BudgetImport, ctx: &ImportContext<'_>) -> Result<StackResourceState> {
        // No controller, so there are no fields to save, only the outputs.
        ctx.ready((), BudgetAlertOutputs { budget_name: data.budget_name })
    }
}

Each importer ships at least one fixture, a sample of the template's outputs, and alien extensions test, and alien release from the extension's workspace, refuse an importer without one. Testing covers fixtures.

Register the resource

budget/hooks/src/lib.rs
fn register(ext: &mut Extension) {
    ext.resource::<BudgetAlert>()
        .cloudformation_emitter(Platform::Aws, CloudFormation)
        .terraform_emitter(Platform::Aws, Terraform)
        .importer(Platform::Aws, Importer);
}

alien_extension_sdk::export!("budget", register);

The workspace manifest names the two crates. There is no controller entry:

budget/Cargo.toml
[workspace]
members = ["types", "hooks"]

[workspace.metadata.alien-extension]
hooks = "hooks"
types = "types"

Try it

cd budget
alien extensions test
alien extensions build
cd ..
alien render --format cloudformation --stack alien.ts
alien release

alien render prints the template your customers get, with the AWS::Budgets::Budget next to Alien's own resources. The customer's security team reviews it there before applying it.

Next

  • Custom resources: emitters, importers, links, and which setup paths each part turns on
  • DNS zone: a custom resource with controllers on AWS, Google Cloud, and Azure
  • Releases: what alien release checks before it ships an extension

On this page