Connecting Resources

The connectTo property wires resources together inside a Stacktape stack. Adding a resource name to a workload's connectTo list automatically grants IAM permissions, injects STP_* environment variables with connection details, and — for databases and Redis caches — opens security group access. One line replaces manual IAM policies, networking rules, and environment configuration.

When to use

Use connectTo whenever one resource needs to interact with another at runtime. A Lambda function querying a database, a web service publishing to a queue, a deployment script running migrations — all are connectTo use cases. It is the default mechanism for resource-to-resource access and should be your first choice over manual IAM and environment configuration.

When NOT to use

Skip connectTo when you need permissions narrower than the defaults it grants. For example, connectTo gives a workload broad read/write/delete access to a bucket — if you only need read access, use iamRoleStatements with specific actions and set environment variables manually via $ResourceParam(). You cannot selectively reduce the permissions connectTo grants for a given target; it is all-or-nothing per resource.

Basic example

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

  const uploads = new Bucket({});

  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/handler.ts'
    }),
    connectTo: [myDatabase, uploads]
  });

  return {
    resources: { myDatabase, uploads, api }
  };
});

The connectTo: ['myDatabase', 'uploads'] line gives the Lambda function access to both the database and the bucket. Stacktape injects connection details as STP_MY_DATABASE_* and STP_UPLOADS_* environment variables, grants IAM permissions for the bucket, and opens security group access to the database.

Complete Lambda and DynamoDB API example

This minimal TypeScript config wires a Hono-style Lambda API to a DynamoDB table. The connectTo: ['usersTable'] line grants the function DynamoDB read/write access and injects STP_USERS_TABLE_NAME, which your handler can use as the table name for AWS SDK calls.

export default defineConfig(() => {
  const usersTable = new DynamoDbTable({
    primaryKey: {
      partitionKey: { name: 'userId', type: 'string' }
    }
  });

  const apiGateway = new HttpApiGateway({});

  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/handler.ts'
    }),
    connectTo: [usersTable],
    events: [
      {
        type: 'http-api-gateway',
        properties: {
          httpApiGatewayName: 'apiGateway',
          method: '*',
          path: '/{proxy+}'
        }
      },
      {
        type: 'http-api-gateway',
        properties: {
          httpApiGatewayName: 'apiGateway',
          method: '*',
          path: '/'
        }
      }
    ]
  });

  return {
    resources: { usersTable, apiGateway, api }
  };
});

What connectTo does

When you add a resource name to connectTo, Stacktape performs up to three actions depending on the target resource type:

  1. Grants IAM permissions — the consuming resource's execution role gets a policy allowing it to interact with the target (e.g., read/write objects for buckets, send/receive messages for queues). Network-bound resources like relational databases and Redis caches don't use IAM for data-plane access.

  2. Opens security group access — for relational databases and Redis caches, Stacktape creates security group rules allowing the consuming resource to reach the target on the correct port. See the Lambda function and relational database pages for VPC placement details.

  3. Injects environment variables — Stacktape injects connection parameters as STP_[RESOURCE_NAME]_[PARAM] environment variables into the consuming resource. The exact set of injected variables depends on the target resource type, documented in the tables below.

Environment variable naming

Stacktape converts the resource name and parameter name to UPPER_SNAKE_CASE with the STP_ prefix:

STP_[RESOURCE_NAME]_[PARAMETER_NAME]

A resource named myDatabase with parameter connectionString becomes STP_MY_DATABASE_CONNECTION_STRING. A resource named uploads with parameter name becomes STP_UPLOADS_NAME. CamelCase names are split at word boundaries: jobQueue → JOB_QUEUE, usersTable → USERS_TABLE.

Injected variables

The tables below document the environment variables injected by connectTo for each supported target resource type. Each table assumes an illustrative resource name shown in the heading — your actual variable names follow the STP_[RESOURCE_NAME]_[PARAM] pattern based on the name you give the resource in your config. Additional parameters beyond what is listed here may be accessible via $ResourceParam().

Relational database

Assuming a resource named myDatabase:

ParameterExample env varDescription
connectionStringSTP_MY_DATABASE_CONNECTION_STRINGFull connection string
hostSTP_MY_DATABASE_HOSTDatabase hostname
portSTP_MY_DATABASE_PORTDatabase port
readerConnectionStringSTP_MY_DATABASE_READER_CONNECTION_STRINGReader endpoint connection string (Aurora only)
readerHostSTP_MY_DATABASE_READER_HOSTReader endpoint hostname (Aurora only)

Use $Secret() for the database password in your config to keep credentials out of source control. Additional database parameters like dbName and masterUserName are available via $ResourceParam().

Aurora DSQL

Assuming a resource named database:

ParameterExample env varDescription
endpointSTP_DATABASE_ENDPOINTPublic TLS endpoint
portSTP_DATABASE_PORTPostgreSQL port (5432)
databaseNameSTP_DATABASE_DATABASE_NAMEDefault database (postgres)
usernameSTP_DATABASE_USERNAMEBuilt-in role (admin)
regionSTP_DATABASE_REGIONRegion used to sign an IAM token
idSTP_DATABASE_IDCluster ID
arnSTP_DATABASE_ARNCluster ARN

DSQL does not expose a static password or connection string. Generate a short-lived IAM token for each new connection and keep TLS enabled. connectTo grants dsql:DbConnectAdmin on the connected cluster; see Aurora DSQL for the explicit least-privilege path.

Lambda to Postgres example

Use connectTo on the Lambda function to inject database connection variables. For a database resource named mainDatabase, the Lambda reads process.env.STP_MAIN_DATABASE_CONNECTION_STRING.

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

  const api = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/api.ts'
    }),
    connectTo: [mainDatabase]
  });

  return {
    resources: { mainDatabase, api }
  };
});

For databases that restrict access to VPC-only modes, the consuming Lambda function may need VPC placement. See the Lambda function and relational database pages for VPC and accessibility mode configuration.

Bucket

Assuming a resource named uploads:

ParameterExample env varDescription
nameSTP_UPLOADS_NAMEBucket name
arnSTP_UPLOADS_ARNBucket ARN

Additional bucket parameters are available via $ResourceParam(). See the referenceable parameters page for the full list.

Hosting bucket

A hosting bucket exposes the same S3 name and arn variables as a regular bucket, using the hosting resource's name in the variable prefix. connectTo automatically grants access to the underlying S3 bucket; you do not need to know or reference its nested resource name.

EFS filesystem

Assuming a resource named sharedFiles:

ParameterExample env varDescription
idSTP_SHARED_FILES_IDEFS filesystem ID
arnSTP_SHARED_FILES_ARNEFS filesystem ARN

connectTo deliberately does not mount the filesystem. A mount needs a local path and root-directory decision that Stacktape cannot safely infer. Configure the workload's EFS volumeMounts when it needs filesystem access; use connectTo alone when code only needs the ID or ARN.

DynamoDB table

Assuming a resource named usersTable:

ParameterExample env varDescription
nameSTP_USERS_TABLE_NAMETable name
arnSTP_USERS_TABLE_ARNTable ARN
streamArnSTP_USERS_TABLE_STREAM_ARNDynamoDB Streams ARN
endpointSTP_USERS_TABLE_ENDPOINTDev mode only: address of the local DynamoDB Local

In dev mode, local tables run in DynamoDB Local. A workload, local script or frontend connected to them also gets AWS_ENDPOINT_URL_DYNAMODB, which the AWS SDK reads, so new DynamoDBClient({}) reaches the local tables without code changes. A workload connected to both a local and a deployed table does not get it, because one endpoint cannot serve both; pass STP_<TABLE>_ENDPOINT as the endpoint of the client for the local table instead.

SQS queue

Assuming a resource named jobQueue:

ParameterExample env varDescription
arnSTP_JOB_QUEUE_ARNQueue ARN
nameSTP_JOB_QUEUE_NAMEQueue name
urlSTP_JOB_QUEUE_URLQueue URL (used for sending/receiving)

SNS topic

Assuming a resource named notifications:

ParameterExample env varDescription
arnSTP_NOTIFICATIONS_ARNTopic ARN
nameSTP_NOTIFICATIONS_NAMETopic name

Redis cache

Assuming a resource named cache:

ParameterExample env varDescription
hostSTP_CACHE_HOSTPrimary host endpoint (the configuration endpoint of a sharded cluster)
portSTP_CACHE_PORTPort number
connectionStringSTP_CACHE_CONNECTION_STRINGFull URL with the default user's password
readerHostSTP_CACHE_READER_HOSTReader endpoint (clusters without sharding)
readerPortSTP_CACHE_READER_PORTReader port (clusters without sharding)
readerConnectionStringSTP_CACHE_READER_CONNECTION_STRINGFull URL of the reader endpoint (clusters without sharding)

The deployed cluster uses TLS, so its connection string starts with rediss://. In dev mode the local Redis has no TLS, and the connection string starts with redis://. Code that connects with STP_CACHE_CONNECTION_STRING therefore works in both, while code that builds its own URL from the host and port has to switch TLS itself. The local Redis has no reader endpoint.

Event bus

Assuming a resource named events:

ParameterExample env varDescription
arnSTP_EVENTS_ARNEvent bus ARN

The archiveArn parameter is also available via $ResourceParam() — see the referenceable parameters page for all event bus parameters.

User auth pool

Assuming a resource named auth:

ParameterExample env varDescription
idSTP_AUTH_IDCognito User Pool ID
clientIdSTP_AUTH_CLIENT_IDApp client ID
arnSTP_AUTH_ARNUser Pool ARN

Lambda function

Assuming a resource named myFunction:

ParameterExample env varDescription
arnSTP_MY_FUNCTION_ARNFunction ARN

Batch job

Assuming a resource named myJob:

ParameterExample env varDescription
jobDefinitionArnSTP_MY_JOB_JOB_DEFINITION_ARNBatch job definition ARN
stateMachineArnSTP_MY_JOB_STATE_MACHINE_ARNStep Functions state machine ARN (wraps the batch job)

MongoDB Atlas cluster

Assuming a resource named mongo:

ParameterExample env varDescription
connectionStringSTP_MONGO_CONNECTION_STRINGMongoDB connection string

Upstash Redis

Assuming a resource named redis:

ParameterExample env varDescription
hostSTP_REDIS_HOSTRedis host
portSTP_REDIS_PORTRedis port
passwordSTP_REDIS_PASSWORDRedis password
restTokenSTP_REDIS_REST_TOKENREST API token
restUrlSTP_REDIS_REST_URLREST API URL
redisUrlSTP_REDIS_REDIS_URLFull Redis URL

Private service

Assuming a resource named backend:

ParameterExample env varDescription
addressSTP_BACKEND_ADDRESSInternal service address

AgentCore resources

AgentCore targets inject their resource identifiers and grant only the data-plane permissions needed to use that target:

TargetInjected parametersAccess granted
Runtimeid, arn, endpointName, endpointArnInvoke the runtime and configured endpoints
Memoryid, arnCreate, read, search, update, and delete events and memory records
Gatewayid, arn, urlInvoke the gateway
Browserid, arnStart, use, inspect, and stop browser sessions
Code Interpreterid, arnStart, invoke, inspect, and stop code-interpreter sessions

WebSocket API Gateway

Assuming a gateway named realtime:

ParameterExample env varDescription
apiIdSTP_REALTIME_API_IDAPI Gateway ID
urlSTP_REALTIME_URLPublic wss:// client URL
managementEndpointSTP_REALTIME_MANAGEMENT_ENDPOINTHTTPS endpoint used by ApiGatewayManagementApiClient
canonicalDomainSTP_REALTIME_CANONICAL_DOMAINAWS DNS target, useful with external DNS

Connecting to a WebSocket gateway grants only execute-api:ManageConnections, scoped to that API and Stacktape's managed stage. Lambda functions that own a WebSocket route receive this wiring automatically; use explicit connectTo: [realtime] for other producers that need to send messages to clients.

Stacktape does not create a connection registry. Add a DynamoDB table when your application needs broadcasts, rooms, presence, or user-to-connection lookup. See WebSocket API Gateway for the cleanup pattern.

Kafka cluster

Assuming a cluster named events:

ParameterExample env varDescription
arnSTP_EVENTS_ARNAmazon MSK cluster ARN
nameSTP_EVENTS_NAMEPhysical MSK cluster name
bootstrapServersSTP_EVENTS_BOOTSTRAP_SERVERSComma-separated IAM/TLS broker endpoints

connectTo grants Kafka IAM access scoped to the cluster, its topics, and consumer groups, including CreateTopic but excluding AlterTopic and DeleteTopic. It also opens port 9098 from deployed workloads. A Lambda function used as a direct Kafka client must set joinDefaultVpc: true; Lambda Kafka triggers have separate event-source networking. See Kafka cluster.

Additional connectTo targets

The tables above cover resource types with documented connectTo environment variables. Beyond those, connectTo also accepts IAM-permission-only targets — resource types where connectTo adds the required IAM permissions to the consuming workload's execution role but does not have a documented set of injected environment variables. These include:

For these targets, use $ResourceParam() to pass specific parameters as environment variables manually.

In the type definitions, connectTo targets fall into three categories: role-affecting targets (including AWS API resources and AgentCore resources) that modify the consuming workload's IAM role, security-group-affecting targets (relational databases and Redis caches) that open network access, and environment-only targets such as EFS that expose identifiers without guessing additional configuration.

Script-only variables

Scripts have their own documented connectTo environment-variable set that differs from workload connectTo. In addition to the variables shared with workloads, script connectTo documents these script-specific parameters. Notably, a web service target injects STP_[RESOURCE_NAME]_URL only for scripts — workload connectTo does not inject a URL for web services.

Resource typeScript-only parameters
Relational databaseJDBC_CONNECTION_STRING. Aurora also adds READER_JDBC_CONNECTION_STRING
Web serviceURL
Upstash Kafka topicTOPIC_NAME, TOPIC_ID, USERNAME, PASSWORD, TCP_ENDPOINT, REST_URL

Using injected variables in code

Access the STP_* variables through process.env in your application code:

import { Client } from 'pg';

export const handler = async () => {
  const client = new Client({
    connectionString: process.env.STP_MY_DATABASE_CONNECTION_STRING
  });

  await client.connect();
  const result = await client.query('SELECT NOW()');
  await client.end();

  return { statusCode: 200, body: JSON.stringify(result.rows) };
};

For S3 operations, use the injected bucket name:

import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({});

export const handler = async () => {
  await s3.send(
    new PutObjectCommand({
      Bucket: process.env.STP_UPLOADS_NAME,
      Key: 'hello.txt',
      Body: 'Hello, world!'
    })
  );

  return { statusCode: 200, body: 'Uploaded' };
};

IAM permissions from connectTo are applied to the resource's execution role automatically. AWS SDK calls work without explicit credentials — the SDK uses the role's temporary credentials from the environment.

Permissions granted

Stacktape generates IAM policies at deploy time based on the target resource type. The access categories below reflect the documented behavior for each target:

Target resourceAccess granted
BucketRead, write, and delete objects; list bucket contents
Hosting bucketRead, write, and delete objects in its underlying S3 bucket; list bucket contents
DynamoDB tableCRUD operations (get, put, update, delete) + query and scan
SQS queueSend, receive, and delete messages
SNS topicPublish and subscribe
Event busPublish events
Lambda functionInvoke the function
Batch jobSubmit, list, and terminate jobs
User auth poolFull Cognito User Pool control
MongoDB Atlas clusterTemporary credential-less access
Relational databaseNetwork access (security group rules, not IAM)
Aurora DSQLConnect as the built-in admin role on the target cluster (dsql:DbConnectAdmin)
Redis cacheNetwork access (security group rules, not IAM)
AgentCore RuntimeInvoke the runtime and its configured endpoints
AgentCore MemoryUse events and short- and long-term memory records
AgentCore GatewayInvoke the gateway
AgentCore BrowserUse browser sessions and streams
AgentCore Code InterpreterUse code-interpreter sessions
EFS filesystemNo access change from connectTo; use an explicit volume mount for IAM and network wiring
Email senderses:SendEmail and ses:SendRawEmail, scoped to the exact identity and configuration set
Kafka clusterIAM cluster/topic/group access and port 9098 network access; no topic deletion or alteration

Relational databases and Redis caches are network-bound resources — data-plane access is controlled through VPC security groups rather than IAM policies. Stacktape opens the correct port between the consuming resource and the target automatically.

Multi-container workloads, state machines, OpenSearch domains, Kinesis streams, and event buses are also valid connectTo targets that affect the consuming workload's IAM role. For the final deployed policy, inspect the generated CloudFormation template, for example with stacktape synth.

The exact IAM policy statements generated at deploy time may include additional supporting actions (e.g., listing, describing). For the authoritative policy, inspect the generated CloudFormation template or the deployed stack's IAM roles in the AWS Console.

Custom permissions with iamRoleStatements

When you need access to an AWS service not covered by connectTo, or need different permissions than connectTo provides, use iamRoleStatements:

export default defineConfig(() => {
  const uploads = new Bucket({});

  const reader = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/reader.ts'
    }),
    environment: { BUCKET_NAME: "$ResourceParam('uploads', 'name')" },
    iamRoleStatements: [
      {
        Resource: ["$ResourceParam('uploads', 'bucketArn')/*"],
        Action: ['s3:GetObject']
      }
    ]
  });

  return {
    resources: { uploads, reader }
  };
});

In this example, the reader function gets read-only access to the bucket via iamRoleStatements instead of the broad read/write/delete access that connectTo would grant. The $ResourceParam('uploads', 'bucketArn') directive resolves to the bucket's ARN at deploy time. The /* suffix targets objects inside the bucket — s3:GetObject acts on individual objects, so the IAM resource must be arn:aws:s3:::bucket-name/* rather than the bucket ARN alone. The bucket name is injected manually via $ResourceParam(). Always verify the exact parameter key for each resource type on the referenceable parameters page before using $ResourceParam in IAM resource ARNs — parameter keys vary by resource type and may differ from the connectTo environment variable names.

The iamRoleStatements property adds a separate IAM policy alongside any auto-generated policies. If you use both connectTo and iamRoleStatements targeting the same resource, both policies apply — iamRoleStatements does not override or narrow connectTo permissions.

Scripts with connectTo

Scripts support connectTo for running local commands that need access to deployed resources — database migrations, seed scripts, or health checks:

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

  const bastion = new Bastion({});

  return {
    resources: { myDatabase, bastion },
    scripts: {
      migrate: {
        type: 'local-script-with-bastion-tunneling',
        properties: {
          bastionResource: 'bastion',
          executeCommand: 'npx prisma migrate deploy',
          connectTo: ['myDatabase']
        }
      }
    }
  };
});

Run the script with stacktape script run:

stacktape script run migrate --stage production --region eu-west-1

The local-script-with-bastion-tunneling type tunnels connections through a bastion host, giving your local machine secure access to VPC-only databases. The injected environment variables are automatically adjusted to route through the tunnel. Use local-script for commands that can reach their targets from the machine running Stacktape; use local-script-with-bastion-tunneling when the target must be reached through a bastion tunnel. Three script types support connectTo: local-script, local-script-with-bastion-tunneling, and bastion-script. The example uses executeCommand; local scripts can also use executeCommands, executeScript, or executeScripts, while bastion scripts support executeCommand and executeCommands.

For local-script-with-bastion-tunneling, properties.bastionResource names the bastion host resource used for the tunnel. For bastion-script, properties.bastionResource names the bastion server where the commands are executed. Script execution can also set cwd to control the working directory; local scripts can set stdioMode (capture by default, inherit for interactive prompts, ignore to discard output). See hooks and scripts for details.

Scripts can also define properties.environment for static values, secrets, custom directives, or $ResourceParam() values when a tool expects a specific variable name that differs from the STP_* convention. Use connectTo when the script needs connection variables for specific targets. Use assumeRoleOfResource when the script should run with the same IAM permissions as a deployed workload — such as a function, batch job, web service, private service, worker service, multi-container workload, or SSR frontend.

Resources that use connectTo

The following list covers resources where the connectTo property is available — these are consumers that can connect to other resources. The supported target resources and what each target provides are documented in the injected variables and permissions granted sections above.

Edge Lambda functions are not listed as connectTo consumers in the type definitions. Check the edge function page for what access mechanisms are available and any limitations specific to CloudFront edge runtimes.

VPC and networking

When you connect to relational databases or Redis caches, Stacktape creates security group rules that allow the consuming resource to reach the target on the correct port. Workloads that need to reach VPC-bound databases or Redis caches must be placed in the same VPC — see the Lambda function, web service, and relational database pages for VPC placement configuration.

Lambda functions placed in a VPC lose direct internet access. If your function needs to call external APIs while also connecting to a VPC database, set stackConfig.nat (see below) or use a database with internet-accessible settings for development stages.

NAT: internet access from private subnets

Workloads in the private subnets reach the internet through the stack's NAT, and their outbound traffic leaves through one static Elastic IP per availability zone, which you can allowlist with external services. Three kinds of resources use it:

  • container workloads with usePrivateSubnetsWithNAT: true; they cannot run without NAT, so that flag requires stackConfig.nat;
  • Lambda functions (and SSR frontends) with joinDefaultVpc: true, which have no internet access at all until stackConfig.nat is set, and use it automatically once it is;
  • AgentCore runtimes that connect to a VPC-only database or Redis.

stackConfig.nat chooses the kind of NAT:

stackConfig:
  nat: ha-ec2 # or ec2, or gateway
ec2ha-ec2gateway
What it isOne small EC2 instance (t4g.nano by default), managed by StacktapeOne such instance per availability zone (two by default)AWS-managed NAT Gateway per zone
CostAbout $7 per month, no per-GB chargeAbout $7 per month per zone, no per-GB chargeAbout $32 per month per zone, plus $0.045 per GB processed
Throughput5 Gbps burst on t4g.nano; pick a larger instanceSize for sustained loadSame, per zoneUp to 100 Gbps
When an instance failsAWS replaces it; about three minutes without outbound internetStacktape routes that zone through another zone's instance within about a minute, then back once the replacement is healthy. Outbound calls from that zone fail during that minute and open connections are resetAWS handles it, no visible impact
UpdatesThe instance is replaced when a newer Amazon Linux image or a new instanceSize is deployed, with the same short outageZones are replaced one at a time, with the same short failover per zoneNone needed

Use ec2 for development stages, ha-ec2 for production stacks whose outbound traffic is moderate and can tolerate a minute of failed outbound calls once in a long while, and gateway for high sustained throughput or when every minute of outbound connectivity matters. You can switch kinds on a deployed stack: the VPC, subnets and route tables stay, the previous NAT keeps serving until the new one is ready, and the switch itself only resets the connections open at that moment. The Elastic IPs change, so update any allowlists afterwards.

The object form sets the instance size (ec2, ha-ec2) and the number of zones (ha-ec2, gateway):

stackConfig:
  nat:
    type: ha-ec2
    instanceSize: t4g.small
    availabilityZones: 3

Each failover raises an incident in the Console that says what happened, which zone was affected and that it recovered on its own, so nobody has to go looking in AWS. Stacktape reaches the instances through AWS Systems Manager only; they have no SSH access.

Shared network for non-production stages

Non-production stages of an AWS account and region share one VPC, the stacktape-network stack, instead of creating a VPC each. A new stage's first deploy skips creating a VPC, subnets and an internet gateway, and a team with many preview and feature stages stays under the AWS default limit of 5 VPCs per region. When a stage in it needs outbound internet (stackConfig.nat), it uses one shared NAT instance, the stacktape-network-nat stack: one t4g.nano for every non-production stage, about $7.70 per month in total. The first stage that needs each shared stack creates it while the stage builds, which takes about a minute for the network and about three minutes for the NAT; later stages only use them, and the shared stacks are removed after a day without stages. The shared NAT's size is fixed, so a stage's nat.instanceSize does not apply in the shared network.

Every deploy prints where the stage runs and why:

Network: shared non-production network `stacktape-network` (the stage name `pr-42` marks a non-production stage).
Network: own VPC (the stage name `acme` does not say whether it is production). Set `stackConfig.stageType` or `stackConfig.vpc.shared` to choose.

How a stage is placed. The first deploy that creates networked resources decides, in this order:

  1. stackConfig.vpc.shared: true or false decides.
  2. Otherwise stackConfig.stageType, then the stage type chosen in the Stacktape Console: non-production stages join the shared network, production stages get a VPC of their own.
  3. Otherwise the stage name: names with dev, staging, test, qa, uat, preview, sandbox, pr, feature, feat, e2e or ci join the shared network; prod, production, prd and live get their own VPC.
  4. A name that says neither (main, acme, or one with both kinds of word, such as pre-prod) asks once, "Is stage acme production?", when you deploy from a terminal. In CI, agents, MCP and remote runners nothing is asked: the stage gets a VPC of its own, and the output says how to choose. The answer is not stored for you: add the stackConfig.stageType line the deploy prints so paging, permissions and security checks classify the stage the same way.

Stages with vpc.reuseVpc, MongoDB Atlas clusters, Kafka clusters with function triggers, or stackConfig.nat set to gateway or ha-ec2 always get a VPC of their own, and the output says why.

Placement is fixed. Stages deployed before this behavior existed keep their VPC. A deployed stage cannot move between the shared network and a VPC of its own, because its databases, caches, load balancers and functions would be replaced; to move it, delete the stage and deploy it again. A stage that later becomes production (through stageType, the Console or a rename) keeps running in the shared network, and every deploy warns about it until you set stackConfig.vpc.shared: true to keep it there.

Isolation. Each stage keeps its own security groups, and every workload of the stage also carries a stage security group. In the shared network, databases, Redis and OpenSearch in accessibilityMode: vpc, internal load balancers and Service Connect ports admit only that stage group, so one stage cannot reach another stage's resources by private IP. connectTo works as before. What you give up in the shared network: reaching another stage's resources by private IP (use reuseVpc for that), choosing the CIDR, peering or a transit gateway per stage, and a NAT IP of the stage's own. Anyone who can deploy to the account can still change the shared network; the separation prevents accidental access, not a hostile deployer.

Functions that reach nothing private deploy in seconds. AWS creates network interfaces for each combination of subnets and security groups that VPC functions use. A new combination takes about 4 minutes on the first deploy, and deleting its last function waits up to 20 minutes for AWS to release them. In the shared network, a function with joinDefaultVpc therefore runs in the network's no-access security group when it connects to nothing private: no connectTo target that admits functions by security group (database, Redis, OpenSearch, Kafka) and no EFS mount, in a stage with no accessibilityMode: vpc database, Redis or OpenSearch, no internal load balancer and no Service Connect port. Nothing admits that group, so such a function reaches no stage's private resources, its own stage's included; its outbound access does not change. Every such function in the account and region shares the same network interfaces, so it is created in seconds and deleting it waits for nothing. Other functions keep the stage's security groups. A deployed function keeps its security group, because moving it would create network interfaces again; it moves to the no-access group only when its group changes anyway, for example when it is new or its connections change. The network keeps two idle functions in that group, stacktape-network-keeper-public and stacktape-network-keeper-private, and the janitor invokes them every hour, because AWS removes the network interfaces of functions that are not invoked for about 14 days. They cost nothing in practice.

The shared stacks go away on their own. The network stack includes a small function, the janitor, that checks the shared stacks every hour. Once no stage has used the shared NAT for 24 hours, it removes the NAT; once no stage has used the network for 24 hours, it deletes the network's idle keeper functions and, on a later run once AWS has released their network interfaces, removes the network, its own function included. Deleting a stage never waits for this. The day of grace keeps the NAT for preview and feature stages that come and go, instead of creating it again, about three minutes, for the next one. A stage uses a shared stack while its stack imports it, which lasts until AWS has deleted the stage completely, and each deploy of a stage in the shared network counts as a use too. A failed first deploy, or a stage that stops using nat, is cleaned up the same way. The janitor keeps a shared stack whose VPC holds something Stacktape did not create, such as an instance or an endpoint you added, and says so in its log group, /aws/lambda/stacktape-network-janitor. A deploy that starts while a shared stack is being removed waits for the removal and creates the stack again. The janitor runs within the Lambda free tier and costs well under a cent per month without it.

Permissions for CI with stage-scoped IAM. Deploys through the Stacktape Console and its runners use the connected account's role and need nothing more. A CI role limited to its own stacks also needs, for the shared stacks:

  • cloudformation:DescribeStacks, CreateStack, UpdateStack and UpdateTerminationProtection on arn:aws:cloudformation:<region>:<account>:stack/stacktape-network*/*;
  • ssm:PutParameter on arn:aws:ssm:<region>:<account>:parameter/stacktape/shared-network/*, where each deploy records that it uses the shared stacks;
  • the EC2 actions the network creates: ec2:CreateVpc, ModifyVpcAttribute, CreateSubnet, ModifySubnetAttribute, CreateRouteTable, AssociateRouteTable, CreateRoute, CreateInternetGateway, AttachInternetGateway, CreateVpcEndpoint, CreateTags and ec2:Describe*;
  • for the janitor and the no-access group, which the network gets when it is created or on the next deploy of a stage that uses it: iam:CreateRole, PutRolePolicy, GetRole, PassRole, lambda:CreateFunction, lambda:GetFunction, lambda:UpdateFunctionCode, lambda:UpdateFunctionConfiguration, lambda:InvokeFunction, logs:CreateLogGroup, logs:PutRetentionPolicy, scheduler:CreateSchedule, scheduler:GetSchedule and ec2:CreateSecurityGroup;
  • for the NAT: ec2:AllocateAddress, CreateNetworkInterface, CreateSecurityGroup, AuthorizeSecurityGroupIngress, AuthorizeSecurityGroupEgress, CreateLaunchTemplate, RunInstances, autoscaling:CreateAutoScalingGroup, autoscaling:Describe*, iam:CreateRole, PutRolePolicy, AttachRolePolicy, PassRole, lambda:CreateFunction, lambda:GetFunction, lambda:InvokeFunction, ssm:PutParameter and ssm:GetParameters.

The CI role needs no delete actions: the janitor removes the shared stacks with its own role, which can delete only stacktape-network and stacktape-network-nat, and whose delete actions on their resources apply only while CloudFormation uses it for those deletes.

If you would rather not grant them, set stackConfig.vpc.shared: false; the stage then creates its own VPC as before.

Connecting Resources FAQ

How does connectTo differ from manually setting environment variables?

Manual environment entries can pass dynamic values with $ResourceParam(), but they do not grant IAM permissions or open security group rules. connectTo combines those access changes with the standard STP_[RESOURCE_NAME]_[PARAM] variables, so one line handles permissions, networking, and environment configuration together.

What is the difference between IAM permissions and security groups?

AWS IAM controls which API calls a resource can make (e.g., writing to S3, invoking a Lambda function). Security groups control network traffic between resources at the TCP level (e.g., allowing port 5432 connections to a database). Services like S3 and DynamoDB are accessed over the public AWS API, so they only need IAM. Databases and Redis caches run inside a VPC and need security group rules to allow network traffic. connectTo manages both layers depending on the target resource type.

Can I connect to resources in a different stack?

Not directly through connectTo — it takes names of resources defined within the same Stacktape configuration. To access resources from another stack, set environment variables manually with the target's endpoint or ARN (for example via $ResourceParam()) and configure iamRoleStatements for the required IAM permissions.

What happens if I remove a resource from connectTo?

After you remove a target from connectTo and redeploy, your application code should no longer rely on the automatically managed permissions, network access, or STP_* variables for that target. If the code still needs access, configure it explicitly with environment variables and iamRoleStatements. Removing a target from connectTo does not delete the target resource. It removes the consuming workload's automatically managed IAM permissions, injected variables, and any relevant network access rules.

Can I grant read-only (or otherwise narrower) access with connectTo?

No — connectTo grants a fixed set of permissions per resource type and is all-or-nothing; for a bucket that means broad read/write/delete. To grant narrower permissions like read-only S3 access, skip connectTo for that target, set the connection variables manually via $ResourceParam(), and add only the specific actions you need in iamRoleStatements. You can still use connectTo for other targets on the same resource — the two combine rather than override.

Why can't my Lambda function reach the database I connected to?

connectTo opens the security group rules between the consuming resource and a relational database or Redis cache, but the consumer still has to sit in the same VPC to use them. A Lambda function that isn't placed in the VPC will have the STP_* variables and an open security group rule yet still fail to connect. See the Lambda function and relational database pages for VPC placement. Note that putting a Lambda in a VPC removes its direct internet access — set stackConfig.nat if it also calls external APIs.