List a resource in a workload's connectTo, and Stacktape gives the workload access to it: IAM permissions, STP_* environment variables with the connection details and, for databases and Redis, the security group rules. Use it whenever a function, container or script talks to another resource in the same stack.
The access connectTo grants is fixed per resource type and cannot be narrowed. A bucket target, for example, allows reading, writing and deleting objects. For read-only access, leave the target out of connectTo, pass its name with $ResourceParam() and add only the actions you need with iamRoleStatements.
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:
-
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.
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:
| 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:
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 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:
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:
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
Production stages get a VPC of their own; non-production stages of an account and region share one, the shared non-production network. 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:
stackConfig: nat: ha-ec2 # or ec2, or gatewayec2 | 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):
stackConfig: nat: type: ha-ec2 instanceSize: t4g.small availabilityZones: 3Each 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.
Connecting resources FAQ
How does connectTo differ from setting environment variables myself?
An environment entry with $ResourceParam() passes the value but grants no IAM permissions and opens no security group. connectTo does all three. You can combine both on one workload.
Can I connect to resources in a different stack?
Not with connectTo; it takes resources of the same config. Export the value from the stack that owns the resource and import it in the other one:
# Stack that owns the resource (project shared-infra, stage production)stackConfig: outputs: - name: OrdersQueueUrl value: $ResourceParam('ordersQueue', 'url') export: true - name: OrdersQueueArn value: $ResourceParam('ordersQueue', 'arn') export: true# Stack that uses itresources: worker: type: function properties: packaging: type: js-bundle properties: entryfilePath: ./src/worker.ts environment: - name: ORDERS_QUEUE_URL value: $CfStackOutput('shared-infra-production', 'OrdersQueueUrl') iamRoleStatements: - Effect: Allow Action: ['sqs:SendMessage'] Resource: [$CfStackOutput('shared-infra-production', 'OrdersQueueArn')]$CfStackOutput makes CloudFormation import the export, so the owning stack cannot remove or change that output while another stack uses it. $StackOutput reads the value once at deploy time instead, with no such link. Permissions and network access are not part of the export: add iamRoleStatements, and for a private database put both stacks in a network that can reach it. See Stages and environments.
What happens if I remove a resource from connectTo?
The next deploy removes the workload's permissions, STP_* variables and security group rules for it. The resource itself stays.
Why does the deploy say my function cannot connect to VPC-only resources?
A Lambda function runs outside your VPC unless you set joinDefaultVpc: true. A Redis cluster, a Kafka cluster and a relational database with accessibilityMode: vpc or scoping-workloads-in-vpc are reachable only from inside it, so the CLI stops with CONFIG_FUNCTION_VPC_REQUIRED before it deploys. Set joinDefaultVpc: true on the function. A function in the VPC has no internet access until you set stackConfig.nat, so add it if the function also calls external APIs.
If the function is in the VPC and still times out, check that you connect with the injected STP_* values rather than an address from another stage, and that the database is in the same network as the function.