Skip to content

Configuration

Directives

Directives are built-in functions (prefixed with $) that inject dynamic values into your Stacktape configuration. They let you reference secrets, resource outputs, stage names, files, and cross-stack values without hardcoding anything. Directives bridge the gap between static config and the dynamic reality of deployments where values like database URLs exist only after resources are created.

Why directives exist

A Stacktape configuration file describes your entire infrastructure declaratively. But some values are inherently dynamic:

  • A database connection string is only known after the database is provisioned.
  • A secret should never be committed to source control.
  • The stage name determines which domain prefix to use.
  • A shared infrastructure stack exports values that dependent stacks consume.

Directives solve these problems by deferring value resolution to the right moment: either when Stacktape parses your config (local directives) or when CloudFormation deploys your resources (runtime directives).

Local vs runtime directives

Stacktape divides directives into two categories based on when they resolve:

CategoryResolved whenUse for
LocalStacktape parses your config (before deployment)Stage name, region, file contents, string formatting, CLI args, git info
RuntimeCloudFormation deploys resourcesSecrets, resource parameters, cross-stack imports, runtime string composition

Runtime directives are supported in resources, scripts and cloudformationResources properties that become part of the synthesized template. Directives introduced by supported overrides and transforms are also resolved. Local directives work anywhere, including variables and top-level settings.

Warning: Avoid runtime directives where config parsing needs a concrete local value. Compose runtime values inside template properties, for example with $CfFormat.

Using directives in TypeScript

In TypeScript configuration, Stacktape exposes runtime directive helpers as functions you import from the stacktape package. For local operations like variable access, string interpolation, and file loading, you can use native JavaScript instead: template literals, import, and fs.readFileSync cover most of what $Var, $Format, and $File do in YAML configs.

TypeScript
export default defineConfig(({ stage }) => {  const database = new RelationalDatabase({    engine: new RdsEnginePostgres({      primaryInstance: { instanceSize: 'db.t4g.micro' },      version: '16'    }),    credentials: {      masterUserPassword: $Secret('db-password')    }  });  const api = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: {      DB_CONNECTION_STRING: $ResourceParam('database', 'connectionString'),      STAGE: $Stage(),      REGION: $Region()    },    connectTo: [database]  });  return { resources: { database, api } };});

The examples below import runtime directive helpers like $Secret, $ResourceParam, $CfFormat, $GitInfo, $Stage, and $Region from the stacktape package. For most local operations in TypeScript configs, prefer native JavaScript: template literals instead of $Format, variables instead of $Var, and fs/import instead of $File.

Pass deployment context to your app

The most common use of directives is to give your code values that depend on the deploy: the stage, the region, the commit, or a value you pass on the command line. They resolve when you run stacktape deploy, so one config works for every stage.

TypeScript
export default defineConfig(() => {  const api = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({      entryfilePath: './src/api.ts'    }),    environment: {      STAGE: '$Stage()',      REGION: '$Region()',      GIT_COMMIT: "$GitInfo('commit')",      LOG_LEVEL: "$CliArgs('logLevel', 'info')"    }  });  return { resources: { api } };});

Your code reads them as process.env.STAGE, process.env.GIT_COMMIT and so on. LOG_LEVEL is info unless you deploy with -- --logLevel debug. For values that differ more between stages, such as instance sizes or whole resources, see Stages and environments.

Local directives reference

$Stage()

Returns the current target stage name. Use it to differentiate resource naming, domain prefixes, or feature flags across stages.

TypeScript
export default defineConfig(() => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: { STAGE: $Stage() }  });  return { resources: { handler } };});

In TypeScript, the stage value is also available directly from the defineConfig callback parameter: defineConfig(({ stage }) => { ... }). Use the callback parameter when you need native JavaScript operations like template literals for domain names (e.g., `${stage}-api.example.com`).

$Region()

Returns the AWS region where the stack is being deployed (e.g. us-east-1, eu-west-1).

TypeScript
export default defineConfig(() => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: { DEPLOY_REGION: $Region() }  });  return { resources: { handler } };});

$Format()

In YAML configs, $Format() is the directive-based way to interpolate strings using {} placeholders. Each {} is replaced with the corresponding positional argument. The number of {} placeholders must match the number of additional arguments. Example: $Format('{}-api.example.com', $Stage()) produces dev-api.example.com when the stage is dev.

In TypeScript configs, prefer template literals for ordinary local string composition. For example, `${stage}-api.example.com` achieves the same result. The stage value is available from the defineConfig callback parameter: defineConfig(({ stage }) => { ... }).

$Var()

$Var() references the variables section in directive-based (YAML) config. In YAML, access nested properties with dot notation: $Var().myProperty.nested.

In TypeScript config, use regular JavaScript variables instead: that is clearer and keeps values type-checkable. For example, const instanceSize = 'db.t4g.micro'; and use instanceSize wherever needed.

$File()

Loads and parses a file in one of the supported formats, resolved using Stacktape's configured working directory. Supported formats:

FormatReturns
.envArray of { name, value } objects
.jsonParsed JSON object
.yml / .yamlParsed YAML object
.iniParsed INI object

Access nested properties with dot notation: $File('config.json').database.host. If the file format is not one of the supported types, Stacktape throws a directive error suggesting you use $FileRaw instead.

TypeScript
export default defineConfig(() => {  const envVars: Record<string, string> = {};  readFileSync('.env', 'utf-8')  .split('\n')  .filter(line => line.includes('='))  .forEach(line => {    const [name, ...rest] = line.split('=');    envVars[name.trim()] = rest.join('=').trim();  });  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: envVars  });  return { resources: { handler } };});
Tip: In TypeScript configs, use native import or readFileSync for file loading. The example above parses .env into a Record<string, string> for the environment property's object form. In YAML configs, $File('.env') returns an array of { name, value } objects matching the environment array form. The $File() directive is most useful in YAML configs where file loading isn't built in.

$FileRaw()

Reads a file as a raw UTF-8 string without parsing. Use it when you need the literal file content: for example, embedding a JSON config as a string environment variable or reading a template file.

$GitInfo()

Returns information about the current git repository. Pass the property name as a required string argument: $GitInfo('commit'), $GitInfo('branch'), $GitInfo('username'), or $GitInfo('gitUrl').

Available properties:

PropertyDescription
commitCurrent commit SHA
branchCurrent branch name
usernameGit username
gitUrlRepository URL
TypeScript
export default defineConfig(() => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: {      GIT_COMMIT: $GitInfo('commit'),      GIT_BRANCH: $GitInfo('branch')    }  });  return { resources: { handler } };});

$CliArgs()

Accesses additional CLI arguments passed after -- in the deploy command. Accepts a second optional argument as a default value if the argument isn't provided.

Pass custom arguments when deploying:

stacktape deploy --stage production --region eu-west-1 -- --featureFlag true --apiVersion v2

In your config, reference them with $CliArgs('featureFlag'). The optional second argument provides a fallback: $CliArgs('featureFlag', 'false') returns 'false' if --featureFlag wasn't passed.

$StackOutput()

References an exported output from another deployed CloudFormation stack. The referenced stack must already be deployed. This is a local directive: it fetches the value at config-parse time by querying CloudFormation.

Arguments: $StackOutput('stackName', 'outputName') with an optional third argument for region when importing from a stack in another AWS region.

The stackName is the full CloudFormation stack name. The outputName must match the CloudFormation output key of the referenced stack. Use stacktape status to discover available output keys for a deployed stack.

Warning: The referenced output must be exported from its stack. Unexported outputs cannot be referenced and will cause a deployment error. The referenced stack must also be deployed before the stack that uses the directive.

$Profile()

Returns the name of the AWS profile being used for the current deployment. Useful when you need to pass profile information to scripts or hooks.

$AwsAccountId()

Returns the AWS account ID of the target account. Use it when you need the account ID for ARN construction or cross-account references.

$This()

$This() is a YAML-only directive that returns the raw configuration object. In YAML, access nested properties with dot notation: $This().resources.myApi. In TypeScript, this directive has no import: reference variables and resource objects directly since they are already in scope.

Runtime directives reference

Runtime directives resolve during CloudFormation deployment. Depending on the directive, Stacktape emits CloudFormation-time values such as dynamic references ($Secret, $SsmParam) or intrinsic functions ($CfFormat, $CfStackOutput). The actual values are only available when AWS provisions your resources.

$Secret()

References a secret stored in AWS Secrets Manager. The named secret must be readable by Stacktape during deployment. Create secrets using stacktape secret set or through the Stacktape Console.

TypeScript
export default defineConfig(() => {  const database = new RelationalDatabase({    engine: new RdsEnginePostgres({      primaryInstance: { instanceSize: 'db.t4g.micro' },      version: '16'    }),    credentials: {      masterUserPassword: $Secret('db-password')    }  });  return { resources: { database } };});

Deployment fails with an error if Stacktape cannot fetch the named secret, with a hint to create it using stacktape secret set.

Warning: The secret's VersionId is baked into the CloudFormation template at deploy time. If you update a secret in AWS Secrets Manager after deployment, the running stack continues using the old version until you redeploy. This means secret rotation requires a redeployment to take effect.

When the CLI resolves $Secret() locally, including in stacktape dev and scripts, it reads the current secret value (AWSCURRENT), just as $SsmParam() reads the current parameter value. A prior deployment does not pin local directive resolution. See Secrets for the distinction between local directives and deployed database credentials.

For a secret that stores a JSON object, pass the top-level key as the second argument: $Secret('secret-name', 'key'). The first argument is always the exact secret name, so it can contain dots. Omit the key, or pass '', to use the whole secret.

TypeScript
export default defineConfig(() => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: {      STRIPE_KEY: $Secret('api-keys', 'stripe'),      SENDGRID_KEY: $Secret('api-keys', 'sendgrid')    }  });  return { resources: { handler } };});

The Stacktape 3 form $Secret('secret-name.key') still works and reads the same secret as before: the text before the first . is the secret name, and the next segment is the JSON key. Use the two-argument form in new configurations, and always for a secret whose name contains a dot.

Create a JSON secret with the CLI:

stacktape secret set --region us-east-1

When prompted, provide a name (e.g., api-keys) and a JSON value (e.g., {"stripe": "sk_...", "sendgrid": "SG..."}).

$SsmParam()

References a parameter from AWS Systems Manager Parameter Store. $SsmParam() reads the parameter and uses the secure dynamic reference form (ssm-secure) when AWS reports the parameter type as SecureString; otherwise it uses the standard SSM dynamic reference form (ssm). During deployment, $SsmParam() reads the current parameter version and injects a CloudFormation dynamic reference pinned to that version: updating the SSM parameter requires a redeployment to pick up the new value. Use SSM parameters when integrating with other AWS tools that write to Parameter Store or when managing configuration values outside your Stacktape config.

TypeScript
export default defineConfig(() => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: {      FEATURE_FLAGS: $SsmParam('/myapp/feature-flags'),      DB_HOST: $SsmParam('/prod/database/host')    }  });  return { resources: { handler } };});

SSM parameters support hierarchical paths (e.g., /myapp/prod/database/host). The referenced parameter must exist before deployment: if missing, deployment fails with a directive error.

Note: $Secret resolves values from AWS Secrets Manager. $SsmParam resolves values from SSM Parameter Store. Use $Secret for credentials and sensitive values. Use $SsmParam for configuration parameters, feature flags, and values managed outside Stacktape.

$ResourceParam()

References a parameter from another Stacktape resource in the same stack. The value resolves at deployment time because it depends on CloudFormation-provisioned outputs like URLs, ARNs, and connection strings. See Referenceable parameters for the full list of parameters available per resource type.

TypeScript
export default defineConfig(() => {  const api = new HttpApiGateway({});  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: { API_URL: $ResourceParam('api', 'url') }  });  return { resources: { api, handler } };});

The first argument is the resource name (as defined in the resources object you return from defineConfig). The second argument is the parameter name. If the resource or parameter doesn't exist, Stacktape lists the available options in the error message.

Tip: For most resource-to-resource communication, prefer connectTo which automatically injects environment variables and grants IAM permissions. Use $ResourceParam when you need a value in a non-standard location or when connectTo doesn't cover your use case.

$CfResourceParam()

References a parameter from a raw CloudFormation resource defined in the cloudformationResources section. Use this when integrating with raw CloudFormation resources that aren't managed by Stacktape's resource abstraction.

TypeScript
export default defineConfig(() => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: { TOPIC_ARN: $CfResourceParam('mySnsTopic', 'TopicArn') }  });  return {    resources: { handler },    cloudformationResources: {      mySnsTopic: {        Type: 'AWS::SNS::Topic',        Properties: { TopicName: 'my-notifications' }      }    }  };});

The first argument is the logical ID of the CloudFormation resource. The second argument is the attribute name: a GetAtt attribute such as TopicArn, Arn or DomainName, or a Ref attribute, which returns the resource's primary identifier. For AWS::CloudFormation::CustomResource types, any attribute name is accepted. Available attributes for standard types depend on the CloudFormation resource type; see the AWS CloudFormation documentation for each type's return values.

$CfFormat()

Performs string interpolation at CloudFormation deployment time, similar to $Format() but capable of including runtime directive values as arguments. Use $CfFormat when you need to combine multiple runtime values into a single string. Under the hood, $CfFormat produces a CloudFormation Fn::Sub intrinsic function.

TypeScript
export default defineConfig(() => {  const database = new RelationalDatabase({    engine: new RdsEnginePostgres({      primaryInstance: { instanceSize: 'db.t4g.micro' },      version: '16'    }),    credentials: {      masterUserPassword: $Secret('db-password')    }  });  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: {      JDBC_URL: $CfFormat(      'jdbc:postgresql://{}:{}/{}',      $ResourceParam('database', 'host'),      $ResourceParam('database', 'port'),      $ResourceParam('database', 'dbName')      )    }  });  return { resources: { database, handler } };});

The key difference from $Format(): $CfFormat() accepts other runtime directives as arguments. $Format() only works with locally-resolved values.

$CfStackOutput()

References an exported output from another deployed stack, resolved at CloudFormation deployment time. Unlike $StackOutput() (which fetches the value locally), $CfStackOutput() creates a CloudFormation ImportValue dependency: this means the referenced stack cannot be deleted while this stack exists, protecting shared infrastructure from accidental removal.

TypeScript
export default defineConfig(() => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: {      SHARED_QUEUE_URL: $CfStackOutput('shared-infra-production', 'QueueQueueUrl')    }  });  return { resources: { handler } };});

Arguments: $CfStackOutput('stackName', 'outputName', region?). The stackName is the full CloudFormation stack name. The outputName must match the CloudFormation output key of the referenced stack. Both $StackOutput and $CfStackOutput accept an optional region argument: Stacktape uses it to look up the referenced stack and validate the export exists. The key difference: $StackOutput returns the resolved value at config-parse time, so cross-region lookups work directly. $CfStackOutput returns a CloudFormation ImportValue intrinsic, which only resolves within the deployment region. Use $StackOutput when you need a value from a stack in another region.

Warning: The referenced output must be exported from its stack. Unexported outputs cannot be referenced and will cause a deployment error.
DirectiveResolution timeDeletion protectionUse when
$StackOutput()Config parse time (local)NoneYou want a snapshot of the value; referenced stack can be deleted independently
$CfStackOutput()CloudFormation deploy timeReferenced stack is lockedYou need a live dependency that prevents accidental deletion of shared resources

Directive nesting

Directives can be nested up to two levels deep. A valid 2-level nesting is a directive inside another directive: for example, $CfFormat('{}/api', $ResourceParam('api', 'url')). Three levels of nesting (a directive inside a directive inside a directive) causes an error. In YAML configs, nesting a runtime directive inside a local directive is also not possible because local directives resolve before deployment begins.

If you need what would be three levels, break the innermost level into a variables entry so it resolves first. In YAML, define a variable like stagePrefix: $Format('{}-', $Stage()) and then reference it as $Var().stagePrefix inside the outer directive: this reduces the effective nesting depth to two. In TypeScript, this limit rarely matters because you use plain JavaScript variables for local operations, avoiding the YAML directive nesting chain entirely.

Example: valid 2-level nesting of $ResourceParam inside $CfFormat:

TypeScript
export default defineConfig(() => {  const handler = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/handler.ts' }),    environment: {      API_ENDPOINT: $CfFormat('{}/v1', $ResourceParam('api', 'url'))    }  });  return { resources: { handler } };});

In TypeScript configs, nesting constraints rarely apply because you use native JavaScript for local operations. The nesting rules matter primarily in YAML configs where you compose directives inside directive arguments.

Complete directive summary

DirectiveCategoryArgumentsDescription
$Stage()LocalNoneCurrent stage name
$Region()LocalNoneAWS region
$Profile()LocalNoneAWS profile name
$AwsAccountId()LocalNoneTarget AWS account ID
$Format()Local(template, ...values)String interpolation with {} placeholders
$Var()LocalNone (access via .property)Reference the variables section
$This()LocalNone (access via .property)Reference the raw config object
$File()Local(filePath)Parse .env, JSON, YAML, or INI file
$FileRaw()Local(filePath)Read file as raw string
$GitInfo()Local(property)Git repository information
$CliArgs()Local(argName, defaultValue?)CLI arguments passed after --
$StackOutput()Local(stackName, outputName, region?)Exported output from another deployed stack
$Secret()Runtime(secretName, jsonKey?)AWS Secrets Manager value, or one key of a JSON secret
$SsmParam()Runtime(paramName)SSM Parameter Store value
$ResourceParam()Runtime(resourceName, param)Parameter from a Stacktape resource
$CfResourceParam()Runtime(logicalId, attribute)Parameter from a raw CF resource
$CfFormat()Runtime(template, ...values)Runtime string interpolation via Fn::Sub
$CfStackOutput()Runtime(stackName, outputName, region?)Cross-stack import with deletion lock

When to use directives vs alternatives

Not every dynamic value needs a directive. Consider the alternatives:

NeedBest approach
Pass a database URL to your codeUse connectTo — it grants required IAM permissions and injects commonly needed environment variables
Compose strings from stage/regionIn TypeScript: use template literals. In YAML: use $Format()
Share values across resourcesIn TypeScript: use a variable. In YAML: use variables + $Var()
Read config from a fileIn TypeScript: use import or readFileSync. In YAML: use $File()
Reference a secret credential$Secret() — no alternative; secrets must never be in source control
Build a string from multiple resource outputs$CfFormat() — the only way to compose runtime values into a string
Consume an output from another stack$StackOutput() or $CfStackOutput() depending on whether you need deletion protection

Directives FAQ

What's the difference between $Secret and $SsmParam?

$Secret resolves values from AWS Secrets Manager, which is designed for credentials and sensitive data. $SsmParam resolves values from SSM Parameter Store, which supports both plain String and encrypted SecureString types and is commonly used for configuration values, feature flags, and non-credential settings. Use $Secret for database passwords, API keys, and tokens. Use $SsmParam for configuration that changes between environments or is managed by other AWS tools.

Can I use $ResourceParam to reference a resource in a different stack?

No. $ResourceParam only references resources within the same stack. For cross-stack references, use $StackOutput (local resolution, no deletion protection) or $CfStackOutput (runtime resolution with deletion protection). Both require the referenced output to be exported from its source stack: unexported outputs cannot be referenced and cause a deployment error. See Referenceable parameters for per-resource parameter details.

Why can't I use $Secret in the variables section?

Runtime directives like $Secret produce CloudFormation intrinsic functions that only resolve during deployment. The variables section is processed locally before the CloudFormation template is generated. If you need a secret value in multiple places, reference $Secret('name') directly in each resource property, or use $CfFormat to compose it with other values within a resource.

How do I pass custom values at deploy time without changing the config?

Use $CliArgs() to read arguments passed after -- in the deploy command. For example, stacktape deploy --stage prod -- --dbSize db.r6g.large lets your config read $CliArgs('dbSize'). The optional second argument is a fallback used when the flag isn't passed: $CliArgs('dbSize', 'db.t4g.micro'). This is useful for values that change per-deploy but shouldn't be committed.

What happens if a referenced secret doesn't exist?

In a terminal, stacktape deploy lists the missing secrets and SSM parameters and asks for their values before it changes anything. In a pipeline or for a coding agent, it fails and names them; create them with stacktape secret set first. Database passwords are generated for you. See Secrets.

How does $CfStackOutput prevent accidental deletion?

$CfStackOutput produces a CloudFormation ImportValue intrinsic function. AWS CloudFormation prevents any stack whose outputs are imported by another stack from being deleted. You must delete the consuming stack first (or remove the $CfStackOutput reference) before the shared stack can be removed. Use $StackOutput instead if you don't need this deletion protection.

Can I import an output from a stack in another region?

Use $StackOutput, not $CfStackOutput. $StackOutput fetches the value at config-parse time, so its optional region argument lets it read an export from a stack in a different region. $CfStackOutput produces a CloudFormation ImportValue, which only resolves within the deployment region: cross-region imports don't work with it. Use stacktape status to find the exact outputName (it must match the stack's CloudFormation OutputKey).

How do I access JSON properties from $Secret?

Pass a top-level key as the second argument to read one value from a JSON secret: $Secret('my-secret', 'apiKey'), where my-secret is the secret name and apiKey is a top-level key in the JSON object. Nested key traversal is not supported. The secret value must be valid JSON: if it isn't, Stacktape reports a parsing error.

How do runtime directives resolve in dev mode?

During local resolution, for example in stacktape dev, runtime directives do not emit CloudFormation references. $ResourceParam() reads the value from the deployed stack. $Secret() fetches the secret from Secrets Manager, and $SsmParam() fetches the parameter from SSM. So stacktape dev needs the referenced values to exist in AWS.

How do I keep one config for development and production?

For string values, use $Stage() directly or compose stage-specific names with $Format(), or template literals in TypeScript. Because defineConfig takes a function, you can use normal conditionals for bigger differences, such as a smaller database in dev. Create separate secrets per stage for sensitive values that differ. See Stages and environments.