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
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.
What connectTo does
When you add a resource name to connectTo, Stacktape performs up to three actions depending on the target resource type:
-
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.
-
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.
-
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:
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:
| Parameter | Example env var | Description |
|---|---|---|
connectionString | STP_MY_DATABASE_CONNECTION_STRING | Full connection string |
host | STP_MY_DATABASE_HOST | Database hostname |
port | STP_MY_DATABASE_PORT | Database port |
readerConnectionString | STP_MY_DATABASE_READER_CONNECTION_STRING | Reader endpoint connection string (Aurora only) |
readerHost | STP_MY_DATABASE_READER_HOST | Reader 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:
| Parameter | Example env var | Description |
|---|---|---|
endpoint | STP_DATABASE_ENDPOINT | Public TLS endpoint |
port | STP_DATABASE_PORT | PostgreSQL port (5432) |
databaseName | STP_DATABASE_DATABASE_NAME | Default database (postgres) |
username | STP_DATABASE_USERNAME | Built-in role (admin) |
region | STP_DATABASE_REGION | Region used to sign an IAM token |
id | STP_DATABASE_ID | Cluster ID |
arn | STP_DATABASE_ARN | Cluster 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.
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:
| Parameter | Example env var | Description |
|---|---|---|
name | STP_UPLOADS_NAME | Bucket name |
arn | STP_UPLOADS_ARN | Bucket 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:
| Parameter | Example env var | Description |
|---|---|---|
id | STP_SHARED_FILES_ID | EFS filesystem ID |
arn | STP_SHARED_FILES_ARN | EFS 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:
| Parameter | Example env var | Description |
|---|---|---|
name | STP_USERS_TABLE_NAME | Table name |
arn | STP_USERS_TABLE_ARN | Table ARN |
streamArn | STP_USERS_TABLE_STREAM_ARN | DynamoDB Streams ARN |
endpoint | STP_USERS_TABLE_ENDPOINT | Dev 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:
| Parameter | Example env var | Description |
|---|---|---|
arn | STP_JOB_QUEUE_ARN | Queue ARN |
name | STP_JOB_QUEUE_NAME | Queue name |
url | STP_JOB_QUEUE_URL | Queue URL (used for sending/receiving) |
SNS topic
Assuming a resource named notifications:
| Parameter | Example env var | Description |
|---|---|---|
arn | STP_NOTIFICATIONS_ARN | Topic ARN |
name | STP_NOTIFICATIONS_NAME | Topic name |
Redis cache
Assuming a resource named cache:
| Parameter | Example env var | Description |
|---|---|---|
host | STP_CACHE_HOST | Primary host endpoint (the configuration endpoint of a sharded cluster) |
port | STP_CACHE_PORT | Port number |
connectionString | STP_CACHE_CONNECTION_STRING | Full URL with the default user's password |
readerHost | STP_CACHE_READER_HOST | Reader endpoint (clusters without sharding) |
readerPort | STP_CACHE_READER_PORT | Reader port (clusters without sharding) |
readerConnectionString | STP_CACHE_READER_CONNECTION_STRING | Full 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:
| Parameter | Example env var | Description |
|---|---|---|
arn | STP_EVENTS_ARN | Event 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:
| Parameter | Example env var | Description |
|---|---|---|
id | STP_AUTH_ID | Cognito User Pool ID |
clientId | STP_AUTH_CLIENT_ID | App client ID |
arn | STP_AUTH_ARN | User Pool ARN |
Lambda function
Assuming a resource named myFunction:
| Parameter | Example env var | Description |
|---|---|---|
arn | STP_MY_FUNCTION_ARN | Function ARN |
Batch job
Assuming a resource named myJob:
| Parameter | Example env var | Description |
|---|---|---|
jobDefinitionArn | STP_MY_JOB_JOB_DEFINITION_ARN | Batch job definition ARN |
stateMachineArn | STP_MY_JOB_STATE_MACHINE_ARN | Step Functions state machine ARN (wraps the batch job) |
MongoDB Atlas cluster
Assuming a resource named mongo:
| Parameter | Example env var | Description |
|---|---|---|
connectionString | STP_MONGO_CONNECTION_STRING | MongoDB connection string |
Upstash Redis
Assuming a resource named redis:
| Parameter | Example env var | Description |
|---|---|---|
host | STP_REDIS_HOST | Redis host |
port | STP_REDIS_PORT | Redis port |
password | STP_REDIS_PASSWORD | Redis password |
restToken | STP_REDIS_REST_TOKEN | REST API token |
restUrl | STP_REDIS_REST_URL | REST API URL |
redisUrl | STP_REDIS_REDIS_URL | Full Redis URL |
Private service
Assuming a resource named backend:
| Parameter | Example env var | Description |
|---|---|---|
address | STP_BACKEND_ADDRESS | Internal service address |
AgentCore resources
AgentCore targets inject their resource identifiers and grant only the data-plane permissions needed to use that target:
| Target | Injected parameters | Access granted |
|---|---|---|
| Runtime | id, arn, endpointName, endpointArn | Invoke the runtime and configured endpoints |
| Memory | id, arn | Create, read, search, update, and delete events and memory records |
| Gateway | id, arn, url | Invoke the gateway |
| Browser | id, arn | Start, use, inspect, and stop browser sessions |
| Code Interpreter | id, arn | Start, invoke, inspect, and stop code-interpreter sessions |
WebSocket API Gateway
Assuming a gateway named realtime:
| Parameter | Example env var | Description |
|---|---|---|
apiId | STP_REALTIME_API_ID | API Gateway ID |
url | STP_REALTIME_URL | Public wss:// client URL |
managementEndpoint | STP_REALTIME_MANAGEMENT_ENDPOINT | HTTPS endpoint used by ApiGatewayManagementApiClient |
canonicalDomain | STP_REALTIME_CANONICAL_DOMAIN | AWS 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:
| Parameter | Example env var | Description |
|---|---|---|
arn | STP_EVENTS_ARN | Amazon MSK cluster ARN |
name | STP_EVENTS_NAME | Physical MSK cluster name |
bootstrapServers | STP_EVENTS_BOOTSTRAP_SERVERS | Comma-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 type | Script-only parameters |
|---|---|
| Relational database | JDBC_CONNECTION_STRING. Aurora also adds READER_JDBC_CONNECTION_STRING |
| Web service | URL |
| Upstash Kafka topic | TOPIC_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:
For S3 operations, use the injected bucket name:
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 resource | Access granted |
|---|---|
| Bucket | Read, write, and delete objects; list bucket contents |
| Hosting bucket | Read, write, and delete objects in its underlying S3 bucket; list bucket contents |
| DynamoDB table | CRUD operations (get, put, update, delete) + query and scan |
| SQS queue | Send, receive, and delete messages |
| SNS topic | Publish and subscribe |
| Event bus | Publish events |
| Lambda function | Invoke the function |
| Batch job | Submit, list, and terminate jobs |
| User auth pool | Full Cognito User Pool control |
| MongoDB Atlas cluster | Temporary credential-less access |
| Relational database | Network access (security group rules, not IAM) |
| Aurora DSQL | Connect as the built-in admin role on the target cluster (dsql:DbConnectAdmin) |
| Redis cache | Network access (security group rules, not IAM) |
| AgentCore Runtime | Invoke the runtime and its configured endpoints |
| AgentCore Memory | Use events and short- and long-term memory records |
| AgentCore Gateway | Invoke the gateway |
| AgentCore Browser | Use browser sessions and streams |
| AgentCore Code Interpreter | Use code-interpreter sessions |
| EFS filesystem | No access change from connectTo; use an explicit volume mount for IAM and network wiring |
| Email sender | ses:SendEmail and ses:SendRawEmail, scoped to the exact identity and configuration set |
| Kafka cluster | IAM 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:
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:
Run the script with stacktape script run:
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.
- Lambda function
- Web service
- Private service
- Worker service
- Multi-container workload
- Batch job
- AgentCore Runtime
- SSR frontends — see each resource's page for
connectToon the server workload: Next.js, Astro, Nuxt, SvelteKit, SolidStart, TanStack Start, Remix - Deployment scripts
- Scripts (
local-script,local-script-with-bastion-tunneling,bastion-script)
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 requiresstackConfig.nat; - Lambda functions (and SSR frontends) with
joinDefaultVpc: true, which have no internet access at all untilstackConfig.natis 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:
ec2 | ha-ec2 | gateway | |
|---|---|---|---|
| What it is | One small EC2 instance (t4g.nano by default), managed by Stacktape | One such instance per availability zone (two by default) | AWS-managed NAT Gateway per zone |
| Cost | About $7 per month, no per-GB charge | About $7 per month per zone, no per-GB charge | About $32 per month per zone, plus $0.045 per GB processed |
| Throughput | 5 Gbps burst on t4g.nano; pick a larger instanceSize for sustained load | Same, per zone | Up to 100 Gbps |
| When an instance fails | AWS replaces it; about three minutes without outbound internet | Stacktape 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 reset | AWS handles it, no visible impact |
| Updates | The instance is replaced when a newer Amazon Linux image or a new instanceSize is deployed, with the same short outage | Zones are replaced one at a time, with the same short failover per zone | None 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):
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:
How a stage is placed. The first deploy that creates networked resources decides, in this order:
stackConfig.vpc.shared: trueorfalsedecides.- 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. - Otherwise the stage name: names with
dev,staging,test,qa,uat,preview,sandbox,pr,feature,feat,e2eorcijoin the shared network;prod,production,prdandliveget their own VPC. - A name that says neither (
main,acme, or one with both kinds of word, such aspre-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 thestackConfig.stageTypeline 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,UpdateStackandUpdateTerminationProtectiononarn:aws:cloudformation:<region>:<account>:stack/stacktape-network*/*;ssm:PutParameteronarn: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,CreateTagsandec2: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:GetScheduleandec2: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:PutParameterandssm: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.