Skip to content

Configuration

Connecting resources

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

TypeScript
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.

TypeScript
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)
Tip:

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.

TypeScript
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
Tip:

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:

TypeScript
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:

TypeScript
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' };};
Tip:

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.

Note:

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:

TypeScript
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:

TypeScript
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

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.

Warning:

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:

YAML
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):

YAML
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.

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:

YAML
# 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
YAML
# 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.