Skip to content

Configuration

Configuration files

A Stacktape project has one configuration file in its root, stacktape.ts or stacktape.yml. It lists the resources of your app (functions, containers, databases, buckets) and how they connect. stacktape init writes one for you; this page explains what is in it.

A minimal config

import {  defineConfig,  HttpApiGateway,  LambdaFunction,  HttpApiIntegration,  JsBundleLambdaPackaging} from 'stacktape';export default defineConfig({ projectName: 'my-app', region: 'eu-west-1' }, () => {  const api = new HttpApiGateway({});  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({      entryfilePath: './src/handler.ts'    }),    events: [      new HttpApiIntegration({        httpApiGatewayName: 'api',        method: 'GET',        path: '/'      })    ]  });  return {    resources: { api, handler }  };});

This deploys an HTTP API with one Lambda function behind it. The keys of resources (api, handler) are the resource names you use everywhere else: in connectTo, in directives and in CLI commands such as stacktape logs handler. Deploy it with:

stacktape deploy --stage dev

For TypeScript, add the stacktape package to your project to get the types and resource classes:

npm install stacktape --save-dev

TypeScript or YAML

Both formats produce the same infrastructure. TypeScript is the better default: your editor checks every property, and you can use conditions, loops, functions and imports. YAML suits a small config that does not change per stage. In YAML, each resource has a type and properties; in TypeScript, each type is a class whose constructor takes those properties.

FeatureTypeScriptYAML
Type checking and autocompletionYesWith the VS Code extension
Per-stage valuesAny codeDirectives such as $Stage()
Loops and generated resourcesYesNo
Reuse across filesImportsVariables in one file
Transforms of the generated templateYesNo

To move from YAML to TypeScript, rewrite the resources with the same names and property values, then compare the output with stacktape synth before you deploy. Keep only one config file in the directory.

Project name and region

Declare the project name and region in the first argument of defineConfig, or as top-level keys in YAML. Commands run inside the project then need only --stage: stacktape deploy --stage dev, stacktape logs api --stage dev, stacktape status --stage dev.

Stacktape reads these two values before it runs the config, because it needs the region and project to pick credentials. Write them as plain strings: a variable, an environment variable or another computed value is rejected with an error that shows the supported form.

A --project or --region flag overrides the config for one command. Without a region in the config, it comes from AWS_DEFAULT_REGION, then the machine-wide default (stacktape defaults set), then the AWS profile. Commands that do not load the config, such as stacktape secret get, take only the region from it and never fail because of it.

The defineConfig callback

The callback receives the context of the command that runs the config. Use it for values that differ per stage or region.

PropertyTypeDescription
stagestringThe stage, for example dev or production
regionstringThe AWS region, for example eu-west-1
projectNamestring or undefinedAlways set when the config declares projectName; otherwise the value of --project or the machine-wide default, if any
commandstringThe CLI command, such as deploy, delete or dev
cliArgsReadonly<Record<string, unknown>>The options of the current command. See Command-line options in the config
awsProfilestringThe local AWS profile the command uses
user{ id, name, email } or undefinedThe signed-in Stacktape user. Undefined without a Console account and for local commands such as package, synth and validate

Do not base resource names or sizes on user: the same stage deployed from CI or without an account would then change.

Command-line options in the config

cliArgs holds the options you passed to the current command, keyed by their camelCase option names. Some options have a different internal name: --config arrives as configPath and --project as projectName. Options you did not type are usually not in it, but projectName and region declared in the config are, so do not treat their presence as a command-line override. Every value is unknown, so check its type before you use it.

cliArgs accepts only the command's own options. Pass your own values after -- and read them with the $CliArgs() directive instead. Write each one as --name value; the form --name=value is not split into a name and a value.

stacktape deploy --stage dev --region eu-west-1 --config stacktape.ts -- --seed demo

For this command, cliArgs is { stage: 'dev', region: 'eu-west-1', configPath: 'stacktape.ts' }, and $CliArgs('seed') resolves to 'demo':

TypeScript
import { defineConfig, LambdaFunction, JsBundleLambdaPackaging } from 'stacktape';export default defineConfig(({ cliArgs }) => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: {      // Passed with --config; 'stacktape.ts' when the option was not typed.      CONFIG_FILE: typeof cliArgs.configPath === 'string' ? cliArgs.configPath : 'stacktape.ts',      // Passed after --; 'none' when it is missing.      SEED: "$CliArgs('seed', 'none')"    }  });  return { resources: { handler } };});

Per-stage values and generated resources

The config is ordinary TypeScript. This one gives production a larger database and creates one queue worker per entry in a list:

TypeScript
export default defineConfig(({ stage }) => {  const isProduction = stage === 'production';  const database = new RelationalDatabase({    engine: new RdsEnginePostgres({      version: '16',      primaryInstance: {        instanceSize: isProduction ? 'db.t4g.medium' : 'db.t4g.micro'      }    }),    credentials: {      masterUserPassword: $Secret('db-password')    }  });  const jobs = ['emails', 'invoices'];  const queues = Object.fromEntries(jobs.map((job) => [`${job}Queue`, new SqsQueue({})]));  const workers = Object.fromEntries(  jobs.map((job) => [    `${job}Worker`,    new LambdaFunction({      packaging: new JsBundleLambdaPackaging({ entryfilePath: `./src/workers/${job}.ts` }),      connectTo: [database],      events: [new SqsIntegration({ sqsQueueName: `${job}Queue` })]    })  ])  );  return {    resources: { database, ...queues, ...workers }  };});

For a large config, move such helpers to their own files (for example config/database.ts) and import them in stacktape.ts. YAML has variables and directives such as $Stage() for the simpler cases.

Top-level fields

The only required field is resources.

FieldPurpose
resourcesYour infrastructure: functions, containers, databases, buckets and so on. See Declaring resources
scripts, hooksCommands you run by hand or before and after deploy, delete and dev. See Hooks and scripts
variablesValues reused across the config with $Var(). See Variables and reuse
directivesYour own functions that compute config values at deploy time. See Directives
deploymentConfigRollback, termination protection and artifact retention. See Deploying stacks
stackConfigOutputs, tags, VPC and NAT settings, tracing, and whether the stage is production
providerConfigCredentials for MongoDB Atlas and Upstash
cloudformationResourcesRaw CloudFormation resources. See Overrides and escape hatches

Which file is used

The CLI looks for stacktape.ts, stacktape.yml, stacktape.yaml or stacktape.js in the current directory (or in --cwd). Use --config for a file elsewhere:

stacktape deploy --stage production --config ./infrastructure/stacktape.ts

When the directory has more than one of these files, for example a stacktape.yml left next to its stacktape.ts rewrite or a stacktape.js your TypeScript build wrote, commands stop with CONFIG_FILE_AMBIGUOUS instead of guessing. Pass --config, or delete or rename the file you no longer use.

Use stacktape.ts for defineConfig and the resource classes. A stacktape.js file is loaded as plain JavaScript: it must export the config object itself (the same shape as the YAML file) or a function that returns it. defineConfig and transforms work only in stacktape.ts.

To check a config without deploying, run stacktape validate. It loads the config, resolves resources and builds the CloudFormation template in memory.

Directives

Directives are values that Stacktape resolves when it runs a command, such as a secret or the URL of another resource. You write them as strings like $Secret('db-password'). In TypeScript, the common ones ($Secret, $ResourceParam, $Stage, $Region, $SsmParam) are also functions you can import from stacktape.

DirectiveWhat it returns
$Secret()A secret from AWS Secrets Manager
$ResourceParam()A parameter of a resource in this stack, such as a URL or ARN
$StackOutput()An output of another stack
$Stage(), $Region()The current stage or region
$Format()A string built from other values
$Var()A value from the variables section
$File()The contents of a file

In TypeScript you often do not need $Var(), $Format() or $File(): constants, template literals and readFileSync do the same. Directives that read deployed state, such as $Secret() and $ResourceParam(), are still needed. See Directives for the full list.

TypeScript classes and YAML types

TypeScript classYAML type
LambdaFunctionfunction
EdgeLambdaFunctionedge-lambda-function
WebServiceweb-service
PrivateServiceprivate-service
WorkerServiceworker-service
MultiContainerWorkloadmulti-container-workload
BatchJobbatch-job
NextjsWebnextjs-web
RelationalDatabaserelational-database
DynamoDbTabledynamo-db-table
Redisredis
MongoDbAtlasClustermongo-db-atlas-cluster
UpstashRedisupstash-redis
OpenSearchDomainopen-search-domain
HttpApiGatewayhttp-api-gateway
ApplicationLoadBalancerapplication-load-balancer
NetworkLoadBalancernetwork-load-balancer
Bucketbucket
HostingBuckethosting-bucket
EfsFilesystemefs-filesystem
SqsQueuesqs-queue
SnsTopicsns-topic
EventBusevent-bus
UserAuthPooluser-auth-pool
WebAppFirewallweb-app-firewall
Bastionbastion
StateMachinestate-machine

Nested objects, such as packaging, database engines and events, follow the same rule: type and properties in YAML, a class in TypeScript. Each resource page lists its options.