Add a DNS zone with its own controllers
This extension, named acme, adds a DNS zone, a resource type Alien doesn't have, with every part a custom resource can have, including its own controllers on AWS, Google Cloud, and Azure. To change a resource Alien already creates, see the IAM database authentication example.
Architecture diagram. Left: Alien containing Alien manager, acme hooks, acme controller. Right: Customer cloud containing Deployment containing zone; api.
What you build:
- A
DnsZonecustom resource with template parts, importers, permission sets, a link, and controllers on all three clouds. - A stack that adds a zone and links it to a Worker.
- Tests for the AWS, Google Cloud and Azure controllers, and an importer fixture for each cloud.
Source: examples/extensions/dns-zone.
alien init extensions/dns-zone acmeLayout
The extension is a Cargo workspace with a types, a hooks, and a controller crate:
acme/
├── Cargo.toml # which crate is the hooks, the controller, and the types
├── package.json # the npm package other developers install
├── types/ # the zone's config, outputs, and saved fields, shared by both crates
├── hooks/src/
│ ├── lib.rs # registers everything the extension adds
│ └── dns_zone.rs # the zone's emitters, importers, and link
├── controller/src/
│ ├── lib.rs # registers the controllers for AWS, Google Cloud and Azure
│ ├── aws.rs, gcp.rs, azure.rs
│ └── main.rs, local.rs # the controller alien dev runs
├── permissions/dns-zone/
│ ├── provision.jsonc
│ └── records-write.jsonc
├── tests/import/acme/dns-zone/ # one importer fixture per platform
└── generated/index.ts # written by alien extensions buildThe hooks crate and the controller crate's library each build to one WebAssembly module that runs sandboxed inside Alien. The controller crate's binary, main.rs, holds the zone's local controller, which only alien dev runs. Where extension code runs explains the split.
[workspace]
members = ["types", "hooks", "controller"]
resolver = "2"
# Tells `alien extensions build` which crate is which.
[workspace.metadata.alien-extension]
hooks = "hooks"
controller = "controller"
types = "types"In your stack
import * as alien from "@alienplatform/core"
import acme, { DnsZone } from "./acme/generated"
// A DNS zone the deployment owns. Alien has no DNS resource.
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, and permission to write records
.permissions("api")
.build()
export default new alien.Stack("my-app")
.extensions([acme])
.add(zone, "frozen")
.add(api, "live")
.permissions({ profiles: { api: {} } })
.build()Register the extension
register lists everything the extension adds, the way Alien registers its own resources:
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 cloud services the zone needs, the Cloud DNS API on Google Cloud and the Microsoft.Network resource provider on Azure. Alien enables them along with the ones its own resources need. The zone's controllers are registered in the controller crate, below.
The DNS zone
DnsZone is a custom resource. Its type lives in the types crate, which the hooks, the controller, and the generated TypeScript share:
/// 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,
}
/// 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>,
}AwsDnsZoneImport, the outputs the AWS template returns, is a struct with one zone_id field. The Google Cloud and Azure types follow the same pattern, except that Google Cloud's import and fields hold a zone_name.
Emitters
An emitter writes the zone's part of each setup template, with the same traits and helpers as Alien's own resources:
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])
}
/// The template output the importer reads after initial setup.
fn emit_import_ref(&self, ctx: &EmitContext<'_>) -> Result<CfExpression> {
Ok(CfExpression::object([(
"zoneId",
CfExpression::ref_(required_logical_id(ctx)?),
)]))
}
}The Terraform emitters write google_dns_managed_zone on Google Cloud, and the matching zone resources on AWS and Azure. In a pull deployment through Helm, Helm creates nothing in the cloud, so the Helm emitter writes an entry in values.yaml where the customer names a zone they already have:
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() },
}),
)
}
}Importer and link
A frozen zone is set up from the template: the admin applies it, and the importer turns the template's outputs into the controller's saved fields. The setup CLI refuses a controller's cloud calls, so it can't create the zone.
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,
)
}
}
/// What a linked workload gets.
pub fn link(outputs: &DnsZoneOutputs) -> Link {
Link::new()
.env("ACME_ZONE_ID", &outputs.zone_id)
.permission_set("acme/dns-zone/records-write")
}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.
The zone's controller gets those fields on its first step. A worker that links the zone gets ACME_ZONE_ID and the records-write permission set.
Permission sets
Each file holds one permission set, in the format of Alien's own. An id is <extension>/<type>/<name>:
{
"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": ["*"] }
}
}
],
"gcp": [
{
"grant": {
"permissions": [
"dns.managedZones.create",
"dns.managedZones.get",
"dns.managedZones.delete",
"dns.changes.create",
"dns.resourceRecordSets.list",
"dns.resourceRecordSets.delete"
]
},
// Reading a zone tells a create or delete whether a zone with its name is the one it made.
// Deleting a record set takes `dns.changes.create` too. Covers every managed zone in the
// project, not only this zone: Alien binds a Google Cloud grant on the project or on one
// topic, subscription, repository or reasoning engine, never on one managed zone.
"binding": {
"stack": { "scope": "projects/${projectName}" },
"resource": { "scope": "projects/${projectName}" }
}
}
],
"azure": [
{
// A zone's delete deletes its record sets too. Reading a zone tells a create or delete
// whether the zone at the domain is the one it made.
"grant": {
"actions": [
"Microsoft.Network/dnszones/read",
"Microsoft.Network/dnszones/write",
"Microsoft.Network/dnszones/delete"
]
},
// Covers every DNS zone in the deployment's resource group, not only this zone: Azure
// names a zone by its domain, which no binding variable holds.
"binding": {
"stack": {
"scope": "/subscriptions/${subscriptionId}/resourceGroups/${resourceGroup}"
},
"resource": {
"scope": "/subscriptions/${subscriptionId}/resourceGroups/${resourceGroup}"
}
}
}
]
}
}The grants cover more than this zone, for the reasons the comments give: every hosted zone in the account on AWS, every managed zone in the project on Google Cloud, and every DNS zone in the deployment's resource group on Azure. records-write has the same scope. Initial setup creates an identity for the extension from these sets, and Alien signs the zone controller's calls as that identity, so the customer's cloud audit log shows them apart from Alien's.
Controllers
A controller uses the same model as Alien's own, a state machine with one handler per state. The library has one per cloud. Each builds its requests a different way, and Alien signs and sends them all. Each saves the domain its zone is made for in CreateStart, and its delete uses that domain, since an update that refuses a rename still leaves the new domain in the stack.
AWS
aws.rs uses the official AWS SDK for Route53, with the config ctx.aws_sdk_config() returns. These are its create steps:
#[flow_entry(Create)]
#[handler(state = CreateStart, on_failure = CreateFailed, status = ResourceStatus::Provisioning)]
async fn create_start(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
let zone = ctx.desired_resource_config::<DnsZone>()?;
// Saved by this step, so a CreateZone that runs again after a lost reply sends the same
// reference and finds the zone it made.
self.caller_reference = Some(caller_reference(
ctx.resource_prefix,
&zone.id,
SystemTime::now(),
));
self.domain = Some(zone.domain.clone());
Ok(HandlerAction::Continue {
state: CreateZone,
suggested_delay: None,
})
}
#[handler(state = CreateZone, on_failure = CreateFailed, status = ResourceStatus::Provisioning)]
async fn create_zone(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
let zone = ctx.desired_resource_config::<DnsZone>()?;
let reference = self.caller_reference.clone().ok_or_else(|| {
AlienError::new(ErrorData::CloudPlatformError {
message: "The zone has no caller reference to create it with".to_string(),
resource_id: Some(zone.id.clone()),
})
})?;
let route53 = aws_sdk_route53::Client::new(&ctx.aws_sdk_config().await?);
let zone_id = create_hosted_zone(&route53, &zone, &reference).await?;
// CloudFormation's Ref returns "Z123", so keep that form on both setup paths.
self.fields.zone_id = Some(zone_id.trim_start_matches("/hostedzone/").to_string());
Ok(HandlerAction::Continue {
state: Ready,
suggested_delay: None,
})
}A step can run again after a lost reply, so every handler must be safe to run twice. CreateStart picks the caller reference and saves it before any call, so a CreateZone sent again sends the same one and finds its zone after HostedZoneAlreadyExists. A zone deleted and created again gets a new reference, since Route53 never reuses one. A delete after a create whose reply was lost finds the zone by that reference too, and removes it.
create_hosted_zone sends the call. An error that isn't HostedZoneAlreadyExists goes through aws_sdk_error:
if !error
.as_service_error()
.is_some_and(|error| error.is_hosted_zone_already_exists())
{
// The error with Alien's own code and retry flag for what Route53 answered, so Alien
// runs the step again after a throttled call or one that got no answer.
return Err(aws_sdk_error(error))
.context(failed("Failed to create the Route53 hosted zone"));
}The source also has the rest of create_hosted_zone, delete_hosted_zone, and the Ready, Update, and Delete handlers.
The crate takes the AWS SDK without its HTTP client, since Alien sends each request:
[dependencies]
acme-types = { workspace = true }
alien-extension-sdk = { workspace = true, features = ["controller"] }
# The AWS controller calls Route53, which Alien has no client for. Alien sends each request for
# the controller module, so the client needs no HTTP stack and no runtime.
aws-sdk-route53 = { version = "=1.121.0", default-features = false }
# `#[controller]` derives serde's traits, whose expansion names the `serde` crate.
serde = { version = "1", features = ["derive"] }
serde_json = "1"Google Cloud
Alien has no Cloud DNS client, so gcp.rs writes its requests with CloudRequest::gcp and sends them with ctx.cloud().send(). As on AWS, CreateStart picks a reference and saves it before any call. CreateZone writes it as a label on the zone:
#[handler(state = CreateZone, on_failure = CreateFailed, status = ResourceStatus::Provisioning)]
async fn create_zone(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
let zone = ctx.desired_resource_config::<DnsZone>()?;
let reference = self.create_reference.clone().ok_or_else(|| {
AlienError::new(ErrorData::CloudPlatformError {
message: "The zone has no create reference to create it with".to_string(),
resource_id: Some(zone.id.clone()),
})
})?;
// The name the Terraform module gives the zone, so both setup paths save the same one.
let name = format!("{}-{}", ctx.resource_prefix, zone.id);
let request = CloudRequest::gcp("dns", "POST", &zones_path(ctx)?).json(&json!({
"name": name,
"dnsName": format!("{}.", zone.domain),
"description": format!("The {} zone", zone.id),
"labels": { CREATE_LABEL: reference },
}))?;
let response = ctx.cloud().send(&request)?;
if response.status == 409 {
// Taken: by this step's own earlier run, or by a zone someone else made.
let path = format!("{}/{name}", zones_path(ctx)?);
let existing: ManagedZone = ctx
.cloud()
.send(&CloudRequest::gcp("dns", "GET", &path))?
.ok("Reading the Cloud DNS zone that has the name")?
.json()?;
if existing.labels.get(CREATE_LABEL) != Some(&reference) {
return Err(AlienError::new(ErrorData::CloudPlatformError {
message: format!(
"A Cloud DNS zone named {name} already exists and this resource didn't create it"
),
resource_id: Some(zone.id.clone()),
}));
}
} else {
response.ok("Creating the Cloud DNS zone")?;
}
self.fields.zone_name = Some(name);
Ok(HandlerAction::Continue {
state: Ready,
suggested_delay: None,
})
}A create that finds the name taken takes the zone only when it carries that label. The delete removes only a zone named <resource prefix>-<id> that the create made or the importer read from the template. It deletes the zone's record sets first, since Cloud DNS refuses to delete a zone that holds records besides its apex SOA and NS.
The project comes from ctx.cloud().target(), where the step's calls go:
/// The path of the managed zones of the project the step is for.
fn zones_path(ctx: &ResourceControllerContext<'_>) -> Result<String> {
match ctx.cloud().target() {
Some(CloudTarget::Gcp { project_id, .. }) => {
Ok(format!("/dns/v1/projects/{project_id}/managedZones"))
}
_ => Err(AlienError::new(ErrorData::ResourceConfigInvalid {
message: "The step is not for a Google Cloud project".to_string(),
resource_id: Some(ctx.desired_config.id().to_string()),
})),
}
}Azure
azure.rs sends its requests to Azure Resource Manager with CloudRequest::azure. It reads the resource group's outputs and the zone Azure returns as its own types:
/// The tag a zone's create writes its reference under.
const CREATE_TAG: &str = "create-reference";
/// What the deployment's resource group outputs, read as the controller's own type.
#[derive(Deserialize)]
struct ResourceGroup {
name: String,
}
/// What Azure returns for a zone.
#[derive(Deserialize)]
struct Zone {
id: String,
/// Azure may send `null` for a zone with no tags.
#[serde(default)]
tags: Option<BTreeMap<String, String>>,
}
impl Zone {
fn tag(&self, name: &str) -> Option<&String> {
self.tags.as_ref()?.get(name)
}
}As on Google Cloud, CreateStart saves a reference before any call. CreateZone writes it as a tag, and sends If-None-Match: * so its PUT never takes over a zone already at the domain:
#[handler(state = CreateZone, on_failure = CreateFailed, status = ResourceStatus::Provisioning)]
async fn create_zone(&mut self, ctx: &ResourceControllerContext<'_>) -> Result<HandlerAction> {
let zone = ctx.desired_resource_config::<DnsZone>()?;
let reference = self.create_reference.clone().ok_or_else(|| {
AlienError::new(ErrorData::CloudPlatformError {
message: "The zone has no create reference to create it with".to_string(),
resource_id: Some(zone.id.clone()),
})
})?;
let path = zone_path(ctx, &zone, &zone.domain)?;
// `If-None-Match: *` creates the zone only where there is none, rather than take over
// a zone that is already at the domain.
let request = CloudRequest::azure("PUT", &path)
.query("api-version", API_VERSION)
.header("If-None-Match", "*")
.json(&json!({ "location": "global", "tags": { CREATE_TAG: reference } }))?;
let response = ctx.cloud().send(&request)?;
let created: Zone = if response.status == 412 {
// Taken: by this step's own earlier run, or by a zone someone else made.
let existing: Zone = ctx
.cloud()
.send(&CloudRequest::azure("GET", &path).query("api-version", API_VERSION))?
.ok("Reading the Azure DNS zone at the domain")?
.json()?;
if existing.tag(CREATE_TAG) != Some(&reference) {
return Err(AlienError::new(ErrorData::CloudPlatformError {
message: format!(
"An Azure DNS zone for {} already exists and this resource didn't create it",
zone.domain
),
resource_id: Some(zone.id.clone()),
}));
}
existing
} else {
response.ok("Creating the Azure DNS zone")?.json()?
};
self.fields.zone_id = Some(created.id);
Ok(HandlerAction::Continue {
state: Ready,
suggested_delay: None,
})
}On a 412 the create takes the zone only when it carries that tag. The delete removes only a zone that carries the tag, or the zone the importer read from the template for the stack's domain. Azure deletes a zone's records with the zone.
zone_path reads the subscription from the step's target, and the resource group from ctx.dependency_outputs("default-resource-group"):
/// The path of `zone`'s zone for `domain` in the deployment's resource group.
fn zone_path(ctx: &ResourceControllerContext<'_>, zone: &DnsZone, domain: &str) -> Result<String> {
let Some(CloudTarget::Azure {
subscription_id, ..
}) = ctx.cloud().target()
else {
return Err(AlienError::new(ErrorData::ResourceConfigInvalid {
message: "The step is not for an Azure subscription".to_string(),
resource_id: Some(zone.id.clone()),
}));
};
// Every resource of an Azure deployment depends on its resource group.
let group: ResourceGroup = ctx.dependency_outputs("default-resource-group")?;
Ok(format!(
"/subscriptions/{subscription_id}/resourceGroups/{}/providers/Microsoft.Network/dnsZones/{}",
group.name, domain
))
}Registration
lib.rs registers one controller per cloud, and export_controllers! exports them from the controller module:
use acme_types::DnsZone;
use alien_extension_sdk::controller_prelude::*;
pub mod aws;
pub mod azure;
pub mod gcp;
/// Registers the zone's controller for each cloud.
pub fn register(controllers: &mut Controllers) {
controllers.register(
DnsZone::RESOURCE_TYPE,
Platform::Aws,
aws::AwsDnsZoneController::default(),
);
controllers.register(
DnsZone::RESOURCE_TYPE,
Platform::Gcp,
gcp::GcpDnsZoneController::default(),
);
controllers.register(
DnsZone::RESOURCE_TYPE,
Platform::Azure,
azure::AzureDnsZoneController::default(),
);
}
alien_extension_sdk::export_controllers!(register);main.rs registers the local controller, which alien dev runs as a process on your machine. It imports local_controller_prelude, not controller_prelude:
//! The zone's controller for `alien dev`, which runs it as a process on the developer's machine.
use acme_types::DnsZone;
use alien_extension_sdk::local_controller_prelude::*;
mod local;
fn main() -> std::process::ExitCode {
alien_extension_sdk::run_controllers(|controllers| {
// Records the zone and returns a placeholder id, with no cloud call.
controllers.register(
DnsZone::RESOURCE_TYPE,
Platform::Local,
local::LocalDnsZoneController::default(),
);
})
}Alien runs the module in a sandbox and signs its cloud calls. Controllers shows whose credentials sign them in each place it runs.
Try it
Test and build
cd acme
alien extensions test
alien extensions buildalien extensions test runs the crates' tests natively, and the hooks crate's tests again inside the sandbox Alien runs hooks in. It then runs each importer on its fixtures, natively and in the hooks module, and loads what it imports into the controller module.
The library also builds natively, so cargo test runs the AWS controller's tests against a stand-in for Route53, and the Google Cloud and Azure controllers' tests with controller_module::testing::answer, which answers its calls in Alien's place.
alien extensions build builds the hooks module, the controller module, the local controller's binary for your machine, and generated/index.ts.
Read the template
cd ..
alien render --format terraform --target aws --stack alien.tsThe module has the aws_route53_zone, and the acme/dns-zone/provision grants on the extension's identity. alien render makes no CloudFormation template for this stack, because the api Worker is built from source and a CloudFormation template needs an image. Its CloudFormation package comes from alien release, which builds the image.
Run it locally
alien devalien dev runs a local deployment and starts the zone's local controller as a process on your machine. It gives the zone a placeholder id, so the api Worker gets ACME_ZONE_ID without a cloud account.
Release
alien releaseThe release pins the extension's bundle by digest, with its hooks module and its controller module. You host nothing: Alien runs the controller wherever it drives the deployment.
Next
- Custom resources: emitters, importers, links, and permission sets
- Controllers: where controllers run and whose credentials sign their calls
- Testing: hook tests, controller tests, and importer fixtures
- SDK reference: every trait and helper