Skip to content

Configuration

Hooks and scripts

Scripts are named commands in your config, such as a frontend build or a seed script. Run them with stacktape script run, or attach them to hooks so they run before or after deploy, delete, dev and bucket sync. Hooks run on your machine or CI runner. For database migrations, use a release command instead.

Choose the right tool

Stacktape can run your own code at three points of a deploy. Pick by when the code has to run and what should happen when it fails.

Release commandHooksDeployment script
RunsIn a one-off ECS task in your VPC, with the service's new imageOn your machine or CI runnerAs a Lambda function in your stack
WhenDuring the deploy, before services and functions get the new codeBefore or after deploy, delete, dev and bucket syncAfter every other resource is deployed (after:deploy), or first in a stack delete (before:delete)
If it failsThe deploy stops; running code keeps servingbefore*: the command stops before anything changes. after*: the new version stays live and the command exits with an errorThe deploy fails; the changes stay unless automatic rollback is on
Use it forDatabase migrationsBuilds, tests, seeding, notificationsWork that must run in AWS on every deploy, whoever deploys

Order within a deploy

  1. beforeDeploy hooks run on your machine. A failure stops here.
  2. Stacktape packages and uploads your code.
  3. Release commands run, then services and functions get the new code.
  4. after:deploy deployment scripts run, once everything else in the stack is deployed.
  5. afterDeploy hooks run on your machine.

Scripts

A Stacktape script is a named task in the scripts section of your config. Scripts can run shell commands or JS/TS/Python files. Use connectTo to auto-inject resource connection details as environment variables. Run scripts manually with stacktape script run or attach them to hooks for automatic execution.

Stacktape supports three script types, each suited to different execution and network requirements:

TypeRuns onBest for
local-scriptYour machine or CI runnerBuilds, migrations using local tools, seeding, linting
local-script-with-bastion-tunnelingYour machine, tunneled through a bastion hostRunning local tools against private VPC resources (databases, Redis)
bastion-scriptThe bastion EC2 instance in your VPCDirect VPC network access without local tool requirements

local-script is the right default for most tasks. Use bastion tunneling when your resources have no public endpoint and you need local CLI tools like prisma or psql. Use bastion scripts when you need direct VPC access and only need basic shell commands.

Local script

A local script runs wherever the Stacktape CLI runs: your laptop during development, or the CI runner in a pipeline. This is the most common script type, covering builds, database migrations, linting, and data seeding.

Scripts can run shell commands or JS/TS/Python files. The examples below use executeCommand; see the configuration reference for the full set of execution properties.

TypeScript
export default defineConfig(() => {  const uploads = new Bucket({});  const api = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({      entryfilePath: './src/handler.ts'    }),    connectTo: [uploads]  });  return {    resources: { api, uploads },    scripts: {      seedBucket: {        type: 'local-script',        properties: {          executeCommand: 'node scripts/seed-data.js',          connectTo: ['uploads']        }      },      buildFrontend: {        type: 'local-script',        properties: {          executeCommand: 'npm run build',          cwd: './frontend'        }      }    }  };});

The seedBucket script uses connectTo to receive the same bucket connection details as the api function: injected as environment variables like STP_UPLOADS_NAME. See connecting resources for the full list of variables injected per resource type. The buildFrontend script runs in a subdirectory using cwd. A local script's stdioMode controls its terminal: capture (the default) shows its output in Stacktape's progress output, inherit hands it the terminal, including input, for interactive programs, and ignore discards its output. In captured output and in a failed script's error, Stacktape replaces the secret values it injected into the script, from $Secret, $SsmParam or the secret parameters of connectTo resources, with [redacted].

Local script with bastion tunneling

When your database or Redis cache has no public endpoint, local-script-with-bastion-tunneling runs locally and tunnels connections to VPC-only resources through a bastion host. This lets you keep using local CLI tools (Prisma, psql, redis-cli) against resources that aren't publicly reachable.

TypeScript
export default defineConfig(() => {  const cache = new Redis({    defaultUserPassword: "$Secret('redis', 'password')",    engine: { type: 'valkey-serverless' }  });  const bastion = new Bastion({});  return {    resources: { cache, bastion },    scripts: {      warmCache: {        type: 'local-script-with-bastion-tunneling',        properties: {          bastionResource: 'bastion',          executeCommand: 'node scripts/warm-cache.js',          connectTo: ['cache']        }      }    }  };});

Stacktape runs the script locally while routing network traffic to connected resources through the bastion host.

Bastion script

A bastion script runs directly on the bastion EC2 instance inside your VPC, with output streaming back to your terminal in real-time. Use this when you need direct network access to VPC resources without running any tools locally.

TypeScript
export default defineConfig(() => {  const cache = new Redis({    defaultUserPassword: "$Secret('redis', 'password')",    engine: { type: 'valkey-serverless' }  });  const bastion = new Bastion({});  return {    resources: { cache, bastion },    scripts: {      checkRedis: {        type: 'bastion-script',        properties: {          bastionResource: 'bastion',          executeCommands: [            'yum install -y redis6 2>/dev/null || yum install -y redis',            'redis-cli --tls -h $STP_CACHE_HOST -p $STP_CACHE_PORT PING'          ],          connectTo: ['cache']        }      }    }  };});

A bastion script runs on the bastion host inside your VPC. If your command needs extra tools, make sure they are available on that host (as shown above with yum install) or use local-script-with-bastion-tunneling to keep using your local toolchain.

Running scripts manually

Run any defined script with stacktape script run:

stacktape script run seedBucket

See the script run CLI reference for the complete command options.

Hooks

Hooks attach scripts to deployment lifecycle events so they run automatically. Define hooks in the top-level hooks section by referencing one or more script names from your scripts section.

TypeScript
export default defineConfig(() => {  const api = new LambdaFunction({    packaging: new JsBundleLambdaPackaging({      entryfilePath: './src/handler.ts'    })  });  const website = new HostingBucket({    uploadDirectoryPath: './frontend/dist'  });  return {    resources: { api, website },    scripts: {      buildFrontend: {        type: 'local-script',        properties: {          executeCommand: 'npm run build',          cwd: './frontend'        }      },      smokeTest: {        type: 'local-script',        properties: {          executeCommand: 'node scripts/smoke-test.js'        }      }    },    hooks: {      beforeDeploy: [{ scriptName: 'buildFrontend' }],      afterDeploy: [{ scriptName: 'smokeTest', skipOnLocal: true }]    }  };});

The buildFrontend script runs before every deploy and builds the frontend into ./frontend/dist, where the hosting bucket picks it up. The smokeTest script runs after deploys from CI (skipOnLocal). Each hook takes a list of scripts and runs them in order.

To run database migrations, use a release command rather than a hook: it runs inside the VPC before your services and functions get the new code, and a failure stops the deploy. An afterDeploy hook runs after the new code is live, so its failure fails the command but does not undo the deploy. If the machine that deploys a function has no Docker, which a function's release command needs, run the migration from an afterDeploy hook with connectTo: ['database'], through a bastion if the database is private.

Lifecycle events

Hooks correspond to the before and after phases of the deploy, delete, dev, and bucket sync commands:

HookWhen it firesCommon use
beforeDeployBefore deployment startsBuilds, linting, tests, asset preparation
afterDeployAfter deployment completesSeeding, cache warming, notifications
beforeDeleteBefore stack deletionData exports, backups
afterDeleteAfter stack deletionExternal cleanup, notifications
beforeBucketSyncBefore syncing bucket contentsPre-processing assets
afterBucketSyncAfter syncing bucket contentsCache invalidation, notifications
beforeDevBefore dev mode startsDependency installation, local setup
afterDevAfter dev mode exitsCleanup

stacktape delete runs beforeDelete and afterDelete only when it can load the config, so run it in the project directory if you rely on them.

When a hook fails

A failed hook stops the command with an error, and the hooks listed after it don't run. A beforeDeploy failure therefore stops the deploy before anything changes.

An afterDeploy hook runs after the deployment finished. When it fails, the stack stays deployed on the new version and nothing is rolled back, but stacktape deploy exits with an error, so a CI job fails. Fix the problem and run the script again with stacktape script run.

In the Console, Slack and email, the deploy is still reported as succeeded, because the new version is live. Everyone who is notified about failed deploys also gets a "Deployed, but a hook failed" message that names the hook.

Set onFailure: continue on a hook whose failure should not fail the command, such as a notification. The failure is then printed as a warning:

YAML
hooks:  afterDeploy:    - scriptName: migrate    - scriptName: notifyTeam      onFailure: continue

A hook cannot roll a deploy back. To keep the old version when a check fails, run the check where it can stop the rollout: a release command runs before services and functions get the new code, and an after:deploy deployment script with deploymentConfig.autoRollback: true makes CloudFormation roll the whole deploy back.

Conditional execution

Hook entries can use skipOnCI and skipOnLocal to control where they run.

  • skipOnCI: true skips the hook in CI, such as GitHub Actions or GitLab CI. Use it for local-only actions like opening a browser.
  • skipOnLocal: true runs the hook only in CI. Use it for smoke tests, test reports or notifications, as smokeTest does above.

Environment variables in scripts

Scripts commonly receive environment variables from connectTo and environment, configured inside the script's properties.

connectTo auto-injects connection details for each listed resource as environment variables. The exact variables depend on the resource type: see connecting resources for the full per-resource injection table.

environment lets you define additional variables explicitly. Values support directives like $Secret(), $ResourceParam(), and $Var(), so you can inject secrets and computed values at execution time.

assumeRoleOfResource injects temporary AWS credentials matching the IAM role of a deployed resource, granting the script the same permissions as that resource. The resource must be deployed before the script runs. Most AWS SDKs and CLIs automatically pick up the injected credentials.

Deployment scripts

A deployment script is different: it is a resource, a Lambda function that CloudFormation runs as part of the stack. It runs no matter who or what deploys, and it can reach the VPC without a bastion when you set joinDefaultVpc: true.

YAML
resources:  syncSearchIndex:    type: deployment-script    properties:      trigger: after:deploy      packaging:        type: js-bundle        properties:          entryfilePath: ./scripts/sync-search-index.ts      connectTo:        - search      timeout: 300
  • Every deploy runs it. A stack with an after:deploy script always deploys through CloudFormation, so fast deploys are off for it.
  • A failure fails the deploy. Without automatic rollback, the stack stays in UPDATE_FAILED with the new code running. With deploymentConfig.autoRollback: true, CloudFormation returns the whole stack to the previous version.
  • A before:delete failure stops the delete. The stack ends in DELETE_FAILED; fix the script and delete again.
  • It runs for at most 15 minutes, the Lambda limit.

Run one by hand with stacktape deployment-script run. Options and examples are on the Deployment script page.