4. Configuration grammar (n8n-on-aws/v1)
4.1 Design principles
- One file, one deployment. One file maps to one CDK app and to a set of CloudFormation stacks named
<name>-network,<name>-data,<name>-n8n, plus<name>-edgein us-east-1 when needed. - Describe n8n, not AWS. Top-level sections follow n8n concepts (
topology,database,queue,storage,auth). AWS-only knobs live underruntime.ecs,runtime.eksandaws. - Every resource is
kind-discriminated. One key,kind, picks the implementation, and the other keys of that block belong to that kind only. Pydantic models this as a discriminated union, so a typo or a key that belongs to another kind is an error, not silently ignored. createorexistingeverywhere. Each resource we might own (VPC, ECS or EKS cluster, database, cache, bucket, Cognito, certificate, hosted zone, KMS key, WAF, secrets) acceptskind: existingwith identifiers, or anexternalkind when it lives outside AWS's control.- Layered defaults. Values resolve as: built-in defaults <
profile< the file <--set key=valueon the CLI.n8n-on-aws planshows the resolved value and where each one came from. - No secrets in YAML. Secrets are always references:
{secret: <name-or-arn>}or{secret: <name>, key: <json-key>}. - Escape hatch.
n8n.envpasses any n8n variable as-is, after the generated ones. A variable we generate can be overridden only with a warning.
4.2 Profiles (t-shirt sizes)
A profile only sets defaults; any explicit key wins.
nano | small (default) | medium | large | xlarge | |
|---|---|---|---|---|---|
| topology | single | single | queue | split | multi-main |
| main (vCPU / GiB) | 0.5 / 1 | 0.5 / 2 | 1 / 2 | 1 / 2 | 2 / 4 × 2 |
| webhook | — | — | — | 1..4 × 0.5 / 2 | 2..10 × 1 / 2 |
| workers | — | — | 1..4 × 1 / 2 | 2..10 × 1 / 2 | 4..40 × 2 / 4 |
| database | sqlite (EFS) | aurora-serverless 0.5–2 ACU | aurora-serverless 0.5–8 | aurora-serverless 2–16, 1 reader | aurora r7g.large × 2 |
| queue | none | none | elasticache-serverless | elasticache-serverless | elasticache r7g, 1 replica |
| ingress | cloudfront (origin task) | cloudfront (origin task) | alb | alb | alb |
| nat | none | none | single | per-az | per-az |
| capacity | fargate-spot | fargate | fargate (workers spot) | fargate (workers spot) | fargate |
| indicative cost* | ~$15–25 | ~$60–90 | ~$150–250 | ~$400–700 | $1,500+ |
Memory is sized for n8n and its task runner sidecar, which share the task: a smaller task is killed for memory (exit 137) and restarts in a loop. T22 warns under 1 GiB.
*Ballpark figures for eu-west-1 at low traffic, dominated by NAT, ALB and database minimums. These are to be calibrated with the AWS Pricing API in plan --cost.
4.3 Reference grammar
Notation: type = default, a|b is an enum, ? is optional, ! is required, → is a rule.
apiVersion: n8n-on-aws/v1 # !
name: str # ! ^[a-z][a-z0-9-]{1,24}$ → stack and resource prefix
profile: nano|small|medium|large|xlarge = small
environment: dev|staging|production = production
aws:
account: str? # 12 digits, defaults to the current credentials
region: str? # defaults to the current credentials
tags: {str: str} = {}
permissions_boundary: arn? # applied to every IAM role we create
kms_key: # encryption at rest for data services
kind: aws-managed | create | existing = aws-managed
arn: str # kind=existing
n8n:
version: str = stable # pin it, e.g. "2.37.1"; the runners image uses the same tag
image: str = docker.n8n.io/n8nio/n8n
timezone: str = UTC
license: # see licensing-workbook.md
edition: community | registered-community | business | enterprise = community
activation_key: {secret: str, key: str?} # → required unless community (or certificate)
certificate: {secret: str, key: str?} # offline licence (N8N_LICENSE_CERT), exclusive
usage: # → required for community editions
purpose: internal-business | personal | non-commercial
| service-for-third-parties | embedded-editor
accept_sustainable_use_license: bool # → must be true for community editions
employees: int? # Business plan guidance (< 100)
encryption_key:
kind: generate | existing = generate # generate → Secrets Manager, RETAIN on delete
secret: str # kind=existing
runners:
mode: external | internal = external # internal is deprecated in 2.x
image: str = n8nio/runners
max_concurrency: int = 5
executions:
timeout_seconds: int = -1
max_age_hours: int = 336
max_count: int = 10000
save_on_success: all | none = all
offload_manual_to_workers: bool = true # queue topologies only
public_api: bool = true
metrics: bool = false # N8N_METRICS → /metrics (404 at ingress)
telemetry: bool = false # N8N_DIAGNOSTICS_ENABLED (n8n's default: on)
env: {str: str} = {} # raw n8n variables
secret_env: {str: {secret: str, key: str?}} = {}
topology:
mode: single | queue | split | multi-main # from profile
main: {replicas: int, cpu: int, memory: int} # cpu units, MiB
webhook: {min: int, max: int, cpu: int, memory: int, scale_on_cpu: int = 60}
workers: {min: int, max: int, cpu: int, memory: int,
concurrency: int = 10,
scale_on: queue-depth | cpu = queue-depth,
target: int = 20, # waiting jobs for a faster scale-out, or CPU %
scale_in_minutes: int = 5, # in-flight jobs fit on one worker less
spot: bool}
runtime:
platform: ecs | eks = ecs
ecs:
cluster: {kind: create} | {kind: existing, name: str}
capacity: fargate | fargate-spot | ec2 = fargate
architecture: arm64 | x86_64 = arm64
ec2: # capacity=ec2
instance_types: [str] = [m7g.large] # the first is sized against; more diversify Spot
min: int = 1 # on-demand hosts, always running
max: int = 4
spot_max: int = 4 # Spot hosts for workers, with topology.workers.spot
root_volume_gib: int = 30 # gp3, encrypted
exec: bool = false # ECS Exec; turning it on later needs new tasks
eks:
cluster:
kind: create | existing = create
name: str # existing
version: str = "1.34" # create
compute: auto | managed-nodes = auto # create; auto = EKS Auto Mode (fargate: T20)
node_group: {instance_types: [str], min: int, max: int} # managed-nodes
admin_role_arns: [arn] = []
namespace: str = n8n
chart: {repository: str = oci://ghcr.io/n8n-io/n8n-helm-chart/n8n, version: str = 1.21.0}
keda: install | existing | none = install
load_balancer_controller: install | existing = install # existing cluster: existing (T21)
external_secrets: install | existing = install
network:
vpc:
# kind=create
kind: create
cidr: str = 10.80.0.0/16
azs: 2 | 3 = 2
nat: none | instance | single | per-az # from profile; none → public-IP tasks
endpoints: [s3, ecr, logs, secretsmanager, sts] = [s3]
# kind=existing
# kind: existing
# id: vpc-...
# availability_zones: [eu-west-1a, eu-west-1b] # ! same order as the subnets
# private_subnets: [subnet-...] # ! one per AZ
# public_subnets: [subnet-...] # ! when ingress.public and no CloudFront-only origin
ingress:
kind: cloudfront | alb # from profile: cloudfront (nano, small), alb (medium+)
domain: str? # n8n.example.com; absent → default CloudFront/ALB name
public: bool = true # false → internal ALB (kind=alb only)
allowed_cidrs: [str] = [0.0.0.0/0]
hosted_zone: {kind: lookup, name: str} | {kind: existing, id: str, name: str} | {kind: none}
certificate: {kind: create} | {kind: existing, arn: str} # create needs hosted_zone
idle_timeout_seconds: int = 300
cloudfront: # kind=cloudfront
origin: task | alb = task # task: no ALB, single main replica (finops-workbook.md)
price_class: 100 | 200 | all = 100
waf: {kind: none} | {kind: managed, rate_limit: int = 2000} | {kind: existing, arn: str} # global scope
auth:
mode: none | ip-allowlist | alb-cognito | alb-oidc | cloudfront-cognito = none
cognito: # alb-cognito, cloudfront-cognito
kind: create | existing = create
# create
mfa: off | optional | required = optional
self_signup: bool = false
invite: [email] = [] # initial users
federation: {kind: none} | {kind: oidc, issuer: str, client_id: str, client_secret: {secret: str}}
| {kind: saml, metadata_url: str}
# existing (cloudfront-cognito: a client without secret, callback /_auth/callback)
user_pool_id: str
client_id: str
domain: str # prefix, or the full hosted UI domain
oidc: # alb-oidc
issuer: str
authorization_endpoint: str
token_endpoint: str
user_info_endpoint: str
client_id: str
client_secret: {secret: str, key: str?}
scope: str = openid email
public_paths: [str] = [] # added to the built-in bypass list
session_hours: int = 12
n8n_sso: # n8n's own SSO, Business/Enterprise
kind: none | oidc | saml = none
discovery_endpoint: str # oidc; may reuse the created Cognito pool with `cognito`
client_id: str
client_secret: {secret: str}
metadata_url: str # saml
role_provisioning: disabled | instance_role | instance_and_project_roles = disabled
database:
kind: sqlite | aurora-serverless | aurora | rds | external # from profile
# common to aurora-serverless, aurora, rds
engine_version: str = "17"
backup_retention_days: int = 7
deletion_protection: bool = true # default false when environment=dev
# aurora-serverless
min_acu: float = 0.5 # 0 allowed (scale to zero)
max_acu: float = 4
readers: int = 0
# aurora
instance_class: str = db.r7g.large
instances: int = 2
io_optimized: bool = false
# rds
# instance_class: db.t4g.small
multi_az: bool = false
storage_gb: int = 20
# external (alien or existing database)
host: str
port: int = 5432
name: str = n8n
schema: str = public
credentials: {secret: str} # JSON with username/password
ssl: disable | require | verify-full = verify-full
security_group_id: str? # we add an ingress rule from the n8n tasks
# all
pool_size: int = 4
queue:
kind: none | elasticache-serverless | elasticache | external # from topology/profile
engine: valkey | redis = valkey # created kinds
# elasticache
node_type: str = cache.t4g.small
replicas: int = 1
# external
host: str
port: int = 6379
tls: bool = true
auth: {secret: str}?
cluster: bool = false
security_group_id: str?
key_prefix: str = n8n # N8N_REDIS_KEY_PREFIX for shared Redis
storage:
bucket:
kind: none | create | existing = none
name: str # existing (create derives a name)
prefix: str = "" # existing; n8n data under <prefix>
kms_key_arn: str?
binary_expiry_days: int = 30 # lifecycle on workflows/ only
binary_data: database | filesystem | s3 # default: database (queue) / filesystem (single)
execution_data: database | s3 = database
exchange: # S3 for workflows' heavy data exchange
enabled: bool = false
prefix: str = exchange/
expiry_days: int?
efs: auto | always | never = auto # auto: when sqlite or filesystem
observability:
log_level: error | warn | info | debug = info
log_retention_days: int = 30
container_insights: bool = false
alarms: {email: [email] = []} # alarms always exist; emails notify
dashboard: # one CloudWatch dashboard per deployment
enabled: bool = true # nano profile: false
period_minutes: 1 | 5 | 15 | 60 = 5
range: str = 3h # <n>m, <n>h, <n>d or <n>w
prometheus: none | cloudwatch | amp = none # cloudwatch: agent sidecar on main; amp later
backup:
kind: none | aws-backup = none
retention_days: int = 35
cross_region: str?
finops: # see finops-workbook.md
budget: {monthly_usd: float?, alert_emails: [email] = []}
anomaly_detection: bool = false
schedule: {kind: always-on | office-hours = always-on, timezone: str = UTC,
weekdays: str = MON-FRI, start: str = "08:00", stop: str = "19:00"}
max_monthly_usd: float? # plan and deploy stop above the estimate
usage: # assumptions of the estimate; unset: profile
requests_millions: float? # HTTP requests a month
data_out_gb: float? # GB a month to users and from workflows
data_gb: float? # database, bucket or EFS data
logs_gb: float? # logs ingested a month
average_acu: float? # Aurora Serverless, above min_acu
average_workers: float? # queue modes, above workers.min4.4 Pydantic sketch
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field
class Strict(BaseModel):
model_config = ConfigDict(extra="forbid")
class SecretRef(Strict):
secret: str
key: str | None = None
class _ManagedPostgres(Strict):
engine_version: str = "17"
backup_retention_days: int = Field(7, ge=1, le=35)
deletion_protection: bool = True
pool_size: int = Field(4, ge=1)
class AuroraServerless(_ManagedPostgres):
kind: Literal["aurora-serverless"]
min_acu: float = Field(0.5, ge=0, le=256)
max_acu: float = Field(4, ge=1, le=256)
readers: int = Field(0, ge=0, le=15)
class ExternalPostgres(Strict):
kind: Literal["external"]
host: str
port: int = 5432
name: str = "n8n"
schema_: str = Field("public", alias="schema")
credentials: SecretRef
ssl: Literal["disable", "require", "verify-full"] = "verify-full"
security_group_id: str | None = None
pool_size: int = Field(4, ge=1)
Database = Annotated[
Sqlite | AuroraServerless | AuroraProvisioned | Rds | ExternalPostgres,
Field(discriminator="kind"),
]Cross-field rules (§3.5 of the options study) live in a single @model_validator(mode="after") on the root Deployment model. They return all errors at once, each with a path (database.kind) and a hint. profile defaults are applied in a mode="before" validator by deep-merging the profile dictionary under the user's data. That keeps "explicit beats profile" trivially true, and the plan can report where each value came from.
The JSON Schema is exported from the models (n8n-on-aws schema > schema/v1.json). Samples start with # yaml-language-server: $schema=... for editor completion.
4.5 What the grammar compiles to (sketch)
| Section | ECS | EKS |
|---|---|---|
topology.* | one ECS service per role, task def with n8n + runners containers | Helm values: main, webhookProcessor, worker blocks; runner sidecars on workers (section 4.7) |
workers.scale_on: queue-depth | CloudWatch agent sidecar on main scrapes n8n's queue gauges into the n8n-on-aws namespace; step scaling out on waiting jobs (from zero workers), in when the jobs in flight fit on one worker less, plus a CPU policy that never scales in | KEDA redis scaler on the BullMQ waiting list <prefix>:jobs:wait, target jobs per worker; the prefix is {n8n} on ElastiCache Serverless and bull otherwise. With keda: none: the chart's HPA on CPU, and a C2 warning |
database, queue, storage.bucket | shared <name>-data stack | same |
auth.alb-* | ALB listener rules: bypass list → forward; default → authenticate then forward | ALB Ingress annotations (alb.ingress.kubernetes.io/auth-*) on the editor paths; the public paths are Ingresses of their own without them (section 4.7) |
auth.cloudfront-cognito | Lambda@Edge viewer-request function in the <name>-edge stack (us-east-1); Cognito pool and public client in <name>-n8n, which writes their IDs to an SSM parameter in us-east-1; one CloudFront behavior without the function per public path | same, with the controller's internal ALB as a VPC origin (section 4.7) |
| secrets | ECS secrets: from Secrets Manager | External Secrets Operator, reading Secrets Manager through Pod Identity (section 4.7) |
4.6 Cross-region backup copies
backup.cross_region needs backup.kind: aws-backup and a region other than the deployment's (rules T19). The deployment then gets a stack <name>-backup-copy in that region, with a KMS key (rotation on) and a backup vault. The daily rule of the backup plan copies each recovery point (Aurora or RDS, EFS) to that vault and keeps the copy for backup.retention_days. The n8n encryption-key secret that n8n-on-aws creates is replicated to the same region, encrypted with that key. An existing encryption key is not replicated by this tool, and T19 warns about it: replicate that secret yourself (aws secretsmanager replicate-secret-to-regions).
The vault, its key and its recovery points are retained when the stacks are deleted, like the encryption-key secret. n8n-on-aws destroy prints what remains. The plan's own vault in the deployment region stays too when it holds a recovery point. n8n-on-aws cleanup deletes the helper log groups in the copy region. To remove the vaults on purpose, delete the recovery points (aws backup list-recovery-points-by-backup-vault, then aws backup delete-recovery-point), then the vault (aws backup delete-backup-vault), then schedule the key for deletion and delete the replicated secret.
Restore runbook
Use it when the deployment region is lost or its vault is gone. Every step runs in the cross_region region, and the CDK must be bootstrapped there.
- Find the latest recovery point of the database:
aws backup list-recovery-points-by-backup-vault --backup-vault-name <name>-copy --region <cross_region>. - Create what the restore needs in that region: a subnet group over two subnets and a security group. The copy region may have no default VPC.
- Start the restore (
aws backup start-restore-job --resource-type Aurora) with the metadata ofaws backup get-recovery-point-restore-metadata, and change three values:DBClusterIdentifierto a new name,DBSubnetGroupNameandVpcSecurityGroupIdsto those of step 2, andKmsKeyIdto the copy key (alias/<name>-backup-copy). The metadata names the key of the lost region, which the restore cannot use. The role of the backup plan can restore: it carries the restore policy. Then add an instance to the restored cluster. - Reset the master password with
aws rds modify-db-cluster --master-user-password, and keep it in a Secrets Manager secret in that region. The database credentials secret<name>/databaseis not replicated, so the old password is lost with the region. - Check that the replicated secret
<name>/n8n-encryption-keyexists in that region and holds the value of the lost deployment. n8n cannot read its stored credentials with any other key. - Deploy n8n against the restored cluster: set
aws.regionto the new region,database.kind: externalwith the restored endpoint, the secret of step 4 andsecurity_group_idof the cluster, andn8n.encryption_key: {kind: existing, secret: <name>/n8n-encryption-key}.T19does not apply, becausebackup.cross_regionis left out. - Open n8n, check a workflow and a credential, then re-point DNS.
The copy is a recovery point, so the restore returns the data of the last completed copy, at most one day old with the daily schedule.
4.7 EKS with the official Helm chart
runtime.platform: eks replaces the ECS service stack with the <name>-n8n stack of cdk/eks.py. The network and data stacks stay as they are. The stack contains a cluster (or the lookup of one), the add-ons, the secrets plumbing, and one Helm release of the official n8n chart, pinned by runtime.eks.chart.version.
Chart, not generated manifests. The values come from the same plan as ECS (cdk/helm_values.py): roles and sizes, environment, secrets, task runners, replicas. The chart renders the Kubernetes objects, so it follows n8n's own defaults. Settings the chart derives from a value (database host, Redis host, execution mode, public URLs) are given as values and not as variables, so the two never disagree. The chart is released weekly: the version is pinned, and the tests render the values against it with helm template when helm is available.
Cluster. kind: create builds an EKS Auto Mode cluster, or a cluster with a managed node group (Graviton picks the arm64 image). compute: fargate is rejected (T20): the add-ons do not run well on Fargate pods. admin_role_arns get access entries. kind: existing looks the cluster up by name, adds an access entry for the role that runs kubectl and helm, and installs only what keda and external_secrets ask for. The AWS Load Balancer Controller is installed only on a cluster we create (T21); Auto Mode has it built in. The kubectl provider needs a public or VPC-reachable endpoint, and its layer (kubectl 1.35) supports clusters from 1.34 to 1.36.
Identity and secrets. The n8n service account gets an EKS Pod Identity association with the S3 grants. External Secrets reads Secrets Manager through its own Pod Identity role, and writes one Kubernetes secret, n8n-secrets, which holds the encryption key, the database credentials, the runners token, the licence key and the Redis password. With external_secrets: existing, the operator is yours: its identity must read those secrets. One variable is set twice on purpose: with an external database, the chart sets DB_POSTGRESDB_USER as a plain value, and the secret value follows it and wins.
Workers. With keda: install or existing, KEDA scales workers on the BullMQ waiting list in Redis. This is the signal of the ECS path through another door: ECS publishes n8n's queue gauges to CloudWatch with a sidecar, while on EKS KEDA reads the list itself. observability.prometheus: cloudwatch is ignored on EKS (C2).
Ingress. The AWS Load Balancer Controller creates one internet-facing or internal ALB for all the Ingresses of the release, which share a group. The editor paths carry the login wall (auth-* annotations for alb-cognito or alb-oidc). The public paths of PUBLIC_PATHS are Ingresses without it, ordered before the editor, and /metrics answers 404. The ALB carries the web ACL of ingress.waf through the wafv2-acl-arn annotation.
Finding the ALB. The controller creates the ALB after the Helm release, and helm --wait does not wait for it, so CDK never holds the ALB. The stack names it <name>-n8n (the load-balancer-name annotation, and loadBalancerName in IngressClassParams on Auto Mode), then a custom resource polls DescribeLoadBalancers every 20 seconds, for at most 20 minutes, until the ALB is active. Its ARN, DNS name and hosted zone feed the rest: the Route 53 alias of ingress.domain (to the ALB, or to CloudFront when it is in front), the LoadBalancerDns output and the load balancer section of the dashboard.
CloudFront. With ingress.kind: cloudfront and origin: alb, the shape is the one of ECS: the ALB is internal, in the private subnets, listens on HTTP 80 only, and admits only CloudFront's origin-facing prefix list (security-group-prefix-lists). CloudFront reaches it through a VPC origin built from the looked-up ARN. The distribution, the cloudfront-cognito wall at the edge, the CloudFront web ACL and their dashboard sections are the same code as on ECS (cdk/front.py). The distribution depends on the lookup, which depends on the release, so on deletion CloudFront and the VPC origin go before the release removes the ALB.
Smoke test behind CloudFront (Nov-29, n8n-eks2 in eu-west-3, Auto Mode, cloudfront-cognito, managed CloudFront WAF). The deployment took 40 minutes and destroy 50, of which 3 for the distribution and 7 for the VPC origin, both deleted before the Helm release as designed. The lookup found the ALB by name; Auto Mode honoured the name, the internal scheme and the prefix list together: one internal ALB, HTTP 80 only, whose security group admits only pl-75b1541c (CloudFront origin-facing) and which does not answer from outside. Through CloudFront, the editor redirected to the Cognito hosted page, a user signed in and reached the editor, /healthz and a webhook answered without the wall, and the webhook ran on the worker. /metrics answered 403 from the HideMetrics rule of the WAF. After destroy and cleanup nothing was left in eu-west-3 or us-east-1 (cluster, ALB, distribution, VPC origin, web ACL, edge function, user pool, roles), apart from what #16 tracks: the retained secret, the ACM validation record and the log group of the CloudFront prefix-list lookup, which the lookup's last run recreates at deletion.
Ignored on EKS. finops.schedule: office-hours is not applied (C2). topology.workers.spot is an ECS capacity setting that the profiles turn on, so it is ignored without a finding.
Smoke test (Nov-29, n8n-eks1 in eu-west-3, queue mode on Auto Mode, chart 1.21.0). The deployment took 18 minutes for the n8n stack, and destroy 37 minutes for the three. The editor answered over HTTPS on one ALB, HTTP redirected to HTTPS and /metrics answered 404. A webhook workflow with a Code node ran on the worker, the code in the runner sidecar. KEDA read {n8n}:jobs:wait on ElastiCache Serverless over TLS. A burst of 120 webhook calls to a 30-second Wait put about 110 jobs in the list, and workers went from 1 to 3 in 20 seconds, then back to 1 once the list stayed empty for the 5 minutes of scale_in_minutes. Container Insights published the pod and node metrics of the dashboard. After destroy and cleanup, no cluster, ALB, target group, security group, network interface, volume or role was left. What remained is what the tool retains on purpose (encryption-key secret, ACM validation record) and the four /aws/containerinsights/<name>/ log groups, which cleanup does not delete yet. The test found four defects, fixed since:
- the kubectl handler takes an OCI repository as the full chart reference, so it must not be split into repository and name (403 from ghcr.io);
- chart 1.21 reads
N8N_HOST,N8N_PORTandN8N_PROTOCOLfrom its core secret, so the synchronized secret adds them (CreateContainerConfigErrorotherwise); - the namespace must be deleted before KEDA and External Secrets, or it waits forever on their finalizers (
ROLLBACK_FAILED); - Auto Mode ignores the
group.nameannotation: the group goes inIngressClassParams, or each Ingress gets an ALB of its own.
Teardown. destroy removes the Helm release first, and waits: the controller deletes the ALB, its security groups and its network interfaces before the cluster and the VPC go. The ALB controller, KEDA and External Secrets depend on nothing that outlives the release, so they go after it.