Docs

Custom resources

A custom resource is a resource type your extension adds to Alien, such as a DNS zone. It can be a few lines in the setup template, or a full resource with its own controllers, permissions, and links.

This stack adds a DNS zone from the acme extension and links it to a worker:

alien.ts
import * as alien from "@alienplatform/core"
import acme, { DnsZone } from "./acme/generated" // written by alien extensions build

// Alien has no DNS resource. The acme extension adds one.
const zone = new DnsZone("zone").domain("internal.acme.dev").build()

const api = new alien.Worker("api")
  .code({ type: "source", src: "./api", toolchain: { type: "typescript" } })
  .link(zone) // ACME_ZONE_ID in the worker's environment
  .permissions("api")
  .build()

export default new alien.Stack("my-app")
  .extensions([acme])
  .add(zone, "frozen")
  .add(api, "live")
  .permissions({ profiles: { api: { zone: ["acme/dns-zone/records-write"] } } })
  .build()

On AWS, the zone becomes an AWS::Route53::HostedZone in the setup template. The worker gets the zone's id in ACME_ZONE_ID and permission to write its DNS records.

Pieces

A custom resource provides only the pieces it needs. Each piece turns on one way to set the resource up or manage it:

PieceWhat it turns on
CloudFormation emitterThe CloudFormation setup package
Terraform emitterThe Terraform setup package
Helm emitterHelm setup in a pull deployment. Helm creates nothing in the cloud, so a frozen resource becomes an entry in values.yaml that points at one the customer already has
ControllerInitial setup with the setup CLI, the live lifecycle, and ongoing management
  • A setup path the resource lacks is turned off for every stack that uses it, and the release says why.
  • A resource with no controller is frozen only. Initial setup creates it, and a change to it needs initial setup again.
  • A template modifier never turns a setup path off, because it only changes what Alien already emits.

The budget alert example is a small one, with a CloudFormation and a Terraform emitter and no controller. The DNS zone on this page has every piece, spread over the extension's crates:

acme/
├── Cargo.toml              # the workspace manifest
├── types/src/lib.rs        # the zone's config, outputs, and saved fields
├── hooks/src/dns_zone.rs   # emitters, importers, and the link
├── controller/src/         # one controller per cloud
├── permissions/dns-zone/   # one permission set per file
└── generated/index.ts      # the TypeScript builder, written by alien extensions build

The type

The types crate declares the resource's config and outputs. #[alien_resource] makes the struct a resource type, the way Alien declares its own:

acme/types/src/lib.rs
/// A DNS zone the deployment owns.
#[alien_resource(type = "acme/dns-zone", outputs = DnsZoneOutputs, lifecycles = [Frozen, Live], holds_data = false)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, utoipa::ToSchema, bon::Builder)]
#[serde(rename_all = "camelCase")]
#[builder(start_fn = new)]
pub struct DnsZone {
    /// Lowercase letters, digits and dashes, at most 22 characters, ending in a letter or digit.
    #[builder(start_fn)]
    pub id: String,
    /// The zone's domain, for example "internal.acme.dev".
    pub domain: String,
}

/// What a linked workload sees.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DnsZoneOutputs {
    pub zone_id: String,
}
ArgumentWhat it sets
typeThe type name, <extension>/<type>. A type must sit under its own extension's name, and the extension names alien and experimental are reserved, so two extensions can't declare one type.
outputsThe struct your link and linked workloads read once the resource exists
lifecyclesFrozen, Live, or both. A type with no controller can only be Frozen.
holds_dataWhether deleting the resource can lose your customer's data. When it's true, removing a deployment keeps the resource by default, like a bucket or a database. See Keep or erase data.

Registration

The hooks crate registers each piece in the extension's register function, with an emitter for each setup package and cloud the resource supports, and an importer per cloud:

acme/hooks/src/lib.rs
use acme_types::DnsZone;
use alien_extension_sdk::prelude::*;

mod dns_zone;

fn register(ext: &mut Extension) {
    ext.resource::<DnsZone>()
        .permission_set(include_str!("../../permissions/dns-zone/provision.jsonc"))
        .permission_set(include_str!("../../permissions/dns-zone/records-write.jsonc"))
        .cloudformation_emitter(Platform::Aws, dns_zone::AwsCfEmitter)
        .terraform_emitter(Platform::Aws, dns_zone::AwsTfEmitter)
        .terraform_emitter(Platform::Gcp, dns_zone::GcpTfEmitter)
        .terraform_emitter(Platform::Azure, dns_zone::AzureTfEmitter)
        .helm_emitter(Platform::Kubernetes, dns_zone::KubernetesEmitter)
        .importer(Platform::Aws, dns_zone::AwsImporter)
        .importer(Platform::Gcp, dns_zone::GcpImporter)
        .importer(Platform::Azure, dns_zone::AzureImporter)
        .requires_services(Platform::Gcp, ["dns.googleapis.com"])
        .requires_services(Platform::Azure, ["Microsoft.Network"])
        .link(dns_zone::link);
}

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

requires_services names the Google Cloud APIs and Azure resource providers the type needs. Alien turns them on with the ones its own resource types need.

The controllers live in their own crate. Controllers covers them.

Emitters

An emitter writes the resource's part of a setup template. Emitters implement Alien's own traits, CfEmitter, TfEmitter, and HelmEmitter, with the same helpers Alien's built-in resources use.

acme/hooks/src/dns_zone.rs
pub struct AwsCfEmitter;

impl CfEmitter for AwsCfEmitter {
    fn emit_resources(&self, ctx: &EmitContext<'_>) -> Result<Vec<CfResource>> {
        let zone = resource_config::<DnsZone>(ctx, DnsZone::RESOURCE_TYPE)?;
        let mut hosted_zone = CfResource::new(
            required_logical_id(ctx)?.to_string(),
            "AWS::Route53::HostedZone".into(),
        );
        hosted_zone.properties.insert("Name".into(), CfExpression::String(zone.domain.clone()));
        Ok(vec![hosted_zone])
    }

    fn emit_import_ref(&self, ctx: &EmitContext<'_>) -> Result<CfExpression> {
        Ok(CfExpression::object([("zoneId", CfExpression::ref_(required_logical_id(ctx)?))]))
    }
}
  • emit_resources adds the resources.
  • emit_import_ref names the values the template hands back after initial setup, which the importer reads.
  • TfEmitter works the same way for each cloud's Terraform module. The DNS zone example has one for AWS, Google Cloud, and Azure.

In a pull deployment, Helm creates nothing in the cloud. The HelmEmitter adds an entry to the chart's values.yaml, and the customer fills in a zone they already have, as they do for Alien's own frozen resources on Kubernetes:

acme/hooks/src/dns_zone.rs
pub struct KubernetesEmitter;

impl HelmEmitter for KubernetesEmitter {
    fn emit(&self, ctx: &EmitContext<'_>) -> Result<HelmFragment> {
        Ok(HelmFragment::default().with_infrastructure(InfrastructureValue {
            id: ctx.resource_id.to_string(),
            binding_type: "acme/dns-zone".to_string(),
            service: "route53".to_string(),
            fields: indexmap! { "zoneId".to_string() => "your-zone-id".to_string() },
        }))
    }
}

Importers

The customer's admin sets up a frozen resource from the template or with the setup CLI:

  • The customer's admin applies the CloudFormation or Terraform template. Alien then reads the template's outputs, and the importer turns them into the fields the controller saves.
  • The admin runs initial setup with the setup CLI, which runs the controller from its first state. The CLI refuses the controller's cloud calls, so a resource whose controller calls the cloud is set up from the template.

alien extensions test runs each importer on its fixtures and loads the result into the controller, which must read it back unchanged.

The types crate holds the fields the controller saves, so the importer and the controller read one struct:

acme/types/src/lib.rs
/// What the AWS template returns after initial setup.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AwsDnsZoneImport {
    pub zone_id: String,
}

/// The fields the AWS controller saves. The importer fills them after the admin applies the template.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AwsDnsZoneFields {
    pub zone_id: Option<String>,
}

An importer implements Alien's ResourceImporter trait. ctx.ready(fields, outputs) builds the StackResourceState from the controller's fields and the resource's outputs. Alien adds the type tag and the state version.

acme/hooks/src/dns_zone.rs
pub struct AwsImporter;

impl ResourceImporter for AwsImporter {
    type ImportData = AwsDnsZoneImport;

    fn import(&self, data: AwsDnsZoneImport, ctx: &ImportContext<'_>) -> Result<StackResourceState> {
        let outputs = DnsZoneOutputs { zone_id: data.zone_id.clone() };
        ctx.ready(AwsDnsZoneFields { zone_id: Some(data.zone_id) }, outputs)
    }
}
  • The fields reach the controller on the resource's first step, which is a refresh from Ready, not a create. Registering the deployment never waits for your controller.
  • Every importer ships fixtures. alien extensions test and alien release run the importer on them and load the result into the controller or, for a type with no controller, check its outputs against the outputs type. They fail on a mismatch, such as a renamed field.
  • alien extensions test, and alien release from the extension's workspace, refuse an importer with no fixtures. See Testing.
  • A frozen-only type with no importer for the deployment's platform fails the preflight checks, before initial setup starts. Without one, Alien can't read the resource the template created.

A link says what a workload gets when it links the resource, as environment variables from the outputs and as permission sets.

acme/hooks/src/dns_zone.rs
pub fn link(outputs: &DnsZoneOutputs) -> Link {
    Link::new()
        .env("ACME_ZONE_ID", &outputs.zone_id)
        .permission_set("acme/dns-zone/records-write")
}

A worker with .link(zone) gets ACME_ZONE_ID. It gets acme/dns-zone/records-write when its permission profile doesn't name the zone, as with Alien's own links.

register runs link once on placeholder outputs and records the names of the variables it sets, so they can't depend on the outputs. A deployment fails when a link sets a name it didn't record. A release refuses:

  • a workload whose links set the same variable, such as one worker that links two zones
  • a link that sets a variable the workload sets in its own environment
  • a name that starts with ALIEN_, AWS_, LAMBDA_ or _, which Alien and AWS Lambda reserve

The setup template writes those grants on AWS, Google Cloud, and Azure, for a frozen resource and for a live one. On AWS, a grant on one live resource is refused when the stack changes after setup, so grant a live zone's set to the profile for the whole stack instead: { "*": ["acme/dns-zone/records-write"] }.

Permission sets

Each permission set is one file in Alien's format, the one custom permission sets use, and binding is required. Its id is <extension>/<type>/<name>:

acme/permissions/dns-zone/provision.jsonc
{
  "id": "acme/dns-zone/provision",
  "description": "Create, read and delete the zone",
  "platforms": {
    "aws": [
      {
        "grant": {
          "actions": [
            "route53:ListResourceRecordSets",
            "route53:ChangeResourceRecordSets",
            "route53:DeleteHostedZone"
          ]
        },
        // Covers every hosted zone in the account, not only this zone: Route53 names a zone by
        // an id it assigns at create, which no binding variable holds, and a hosted zone takes
        // no tag condition.
        "binding": {
          "stack": { "resources": ["arn:aws:route53:::hostedzone/*"] },
          "resource": { "resources": ["arn:aws:route53:::hostedzone/*"] }
        }
      },
      {
        // These calls take no resource ARN, so they can only be granted on "*". On "*",
        // ListHostedZonesByName reveals the id of every hosted zone in the account.
        "grant": {
          "actions": ["route53:CreateHostedZone", "route53:ListHostedZonesByName"]
        },
        "binding": {
          "stack": { "resources": ["*"] },
          "resource": { "resources": ["*"] }
        }
      }
    ],
    // …
  }
}

Alien looks up provision, management, and heartbeat by name, as it does for its own types. Here acme/dns-zone/provision covers creating, updating, and deleting the zone.

Those three sets go to the extension's identity. Declare any grant the controller needs in them, with no change to Alien. Alien refuses a set only when it reads stored customer data, changes IAM or who has access, acts as another identity, or names a predefined role. Security lists what each covers.

A permission set can name resources by the names Alien gives them, but not by an id the cloud assigns after it creates one, such as a hosted zone's id. So on AWS, records-write applies to every hosted zone in the account. On Google Cloud it applies to every managed zone in the project, and on Azure to every DNS zone in the deployment's resource group, since a grant there can't name one zone either. The customer's security team sees that in the setup template.

The extension's identity

Initial setup creates one identity for the extension in the customer's cloud, from its permission sets:

CloudIdentity
AWSIAM role
Google CloudService account
AzureUser-assigned managed identity

It trusts Alien's manager the same way the identity behind remote bindings does, and it appears in the setup template the customer reviews. Alien signs your controller's calls as this identity, while Alien's own calls keep the management identity, so the customer's audit log shows which calls came from which. Controllers lists whose credentials sign a controller's calls in each place it runs.

In alien.ts

alien extensions build writes generated/index.ts from the Rust types. Its default export is the extension, which you pass to .extensions(). It also exports a builder per type, such as DnsZone, with a method per config field.

The builders extend CustomResourceType from @alienplatform/core, so they work like Alien's own builders, with .add(zone, "frozen") and .link(zone). An extension you publish for other developers ships its generated/ TypeScript in an npm package.

In the dashboard

A deployment's custom resources appear in its resource list, in one category labeled with the extension's name, such as acme. Each shows its type, status, and outputs. While a step runs, the progress text the controller reports shows next to the resource.

Next

  • Controllers: create, update, and delete the resource in the cloud
  • Testing: test emitters, importers, and controllers before a release
  • DNS zone: the whole custom resource, on AWS, Google Cloud, and Azure

On this page