To import an existing VPC into AWS CDK, call ec2.Vpc.fromLookup() with its vpcId and set the stack's AWS account and region. CDK looks up the network during synthesis and caches its details; it does not create a second VPC or take ownership of the existing one.
Import a VPC by ID: minimal TypeScript example
In a CDK v2 TypeScript project, replace lib/import-vpc-stack.ts with:
import { CfnOutput, Stack, StackProps } from "aws-cdk-lib"; import * as ec2 from "aws-cdk-lib/aws-ec2"; import { Construct } from "constructs"; export class ImportVpcStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); const vpc = ec2.Vpc.fromLookup(this, "ExistingVpc", { vpcId: "vpc-091234567ee1234567", }); new CfnOutput(this, "VpcId", { value: vpc.vpcId }); } }
Replace the example VPC ID with yours. The app configuration below supplies the account and region. This minimal stack only references a network and exports its ID; the later examples are alternatives to its lookup expression.
The minimal stack was type-checked with TypeScript 5.9.3, aws-cdk-lib 2.272.0, and constructs 10.5.0. This revision has not been deployed to an AWS account; synthesis with real VPC lookups requires your credentials and network configuration. See the official Vpc API reference for the lookup contract.
Prerequisites
- AWS CDK Installed: Ensure you have the AWS CDK installed. If not, follow the installation guide.
- Existing VPC: An existing VPC in your AWS account that you intend to import.
- Configured AWS Credentials: Ensure your AWS credentials are properly configured.
Overview
Importing an existing VPC into AWS CDK involves using the fromLookup static method provided by the Vpc construct. This method allows CDK to reference a VPC that already exists in your AWS environment. It's essential to explicitly specify the stack environment (account and region) to enable CDK to locate the VPC accurately.
Defining the Stack Environment
Start by explicitly setting the stack's environment with the AWS account and region. This step ensures that CDK performs the lookup in the correct context.
// bin/app.ts import * as cdk from "aws-cdk-lib"; import { ImportVpcStack } from "../lib/import-vpc-stack"; const app = new cdk.App(); new ImportVpcStack(app, "import-vpc-stack", { env: { region: "us-east-1", // specify your AWS region account: "123456789012", // replace with your AWS account ID }, });
Importing an Existing VPC by Name
To look up by name instead, replace the fromLookup call in the minimal stack with the following. Use a name that identifies exactly one VPC in the selected account and region.
const vpc = ec2.Vpc.fromLookup(this, "ExistingVpc", { vpcName: "YOUR_VPC_NAME", });
Additional Lookup Options
The fromLookup method provides several options to identify the VPC:
- isDefault: Boolean value to match the default VPC.
- tags: Key-value pairs to filter the VPC based on tags.
- vpcId: Directly specify the VPC ID.
These options offer flexibility in selecting the appropriate VPC, especially in environments with multiple VPCs.
Viewing Synthesized CloudFormation
After defining your stack, you can inspect the synthesized CloudFormation template using:
npx aws-cdk synth # Alternatively: cdk synth
The CDK CLI resolves missing lookup context and reruns the app as needed. Inspect the resulting template and cdk.context.json; the minimal example should not declare a new AWS::EC2::VPC resource. Run npx aws-cdk diff before deploying changes to an existing stack.
Deploying the Stack
The minimal stack only publishes an output. Add application resources before deploying if you want to use the VPC for a workload. Check the diff so you understand which resources the stack will own.
npx aws-cdk deploy # Alternatively: cdk deploy
After deployment, check the VpcId stack output against the VPC you selected.
Note: AWS CDK caches VPC details in the cdk.context.json file to optimize future deployments by avoiding repeated lookups. This caching includes values like VPC ID, CIDR blocks, and subnet groups.
Refreshing Cached VPC Values
If the VPC's configuration changes, you need to refresh the cached values to reflect these updates in your CDK stack. Follow these steps to reset the cache:
-
Identify the Cache Key or Number:
npx aws-cdk context # Alternatively: cdk contextThis command lists all cached context values with their corresponding keys and numbers.
-
Reset the Cache:
npx aws-cdk context --reset KEY_OR_NUMBER # Alternatively: cdk context --reset KEY_OR_NUMBERReplace
KEY_OR_NUMBERwith the appropriate identifier from the previous step. -
Synthesize Again:
npx aws-cdk synth # Alternatively: cdk synthCDK will perform a fresh lookup for the VPC, updating the
cdk.context.jsonfile with the latest values.
Importing the Default VPC
To import the default VPC, set the isDefault option to true in the fromLookup method. Since there is only one default VPC per account and region, this configuration is sufficient for CDK to identify it.
// lib/import-vpc-stack.ts const defaultVpc = ec2.Vpc.fromLookup(this, "default-vpc-id", { isDefault: true, });
Ensure that the stack environment is explicitly set to help CDK locate the default VPC accurately.
Importing an Existing VPC by Tags
Tag-based lookup allows you to import a VPC by specifying key-value pairs. This method is particularly useful when managing multiple VPCs with distinct tags.
-
Tag Your VPC: Add a tag to your VPC, for example:
- Key:
app - Value:
web
- Key:
-
Import the VPC Using Tags:
// lib/import-vpc-stack.ts const myVpc = ec2.Vpc.fromLookup(this, "by-tags-id", { tags: { app: "web", }, });
This approach ensures that CDK imports the VPC matching the specified tag criteria.
Importing an Existing VPC by VPC ID
Directly specifying the VPC ID provides a precise method to import a VPC without ambiguity.
// lib/cdk-starter-stack.ts const myVpc = ec2.Vpc.fromLookup(this, "external-vpc", { vpcId: "vpc-091234567ee1234567", // replace with your VPC ID });
This method is straightforward and eliminates the need for additional lookup parameters.
Considerations for Importing Existing VPCs
When importing existing VPCs into your CDK stacks, consider the following limitations and best practices:
-
Explicit Environment Specification:
- Requirement: Always set the stack's environment (
accountandregion). - Reason: CDK needs to know where to perform the VPC lookup accurately.
- Requirement: Always set the stack's environment (
-
Ownership of Existing Resources:
- Limitation: Lookup does not transfer the VPC's existing resources into this stack.
- Implication: Create new resources in the imported VPC as needed, and coordinate changes to existing networking with its owner.
-
Context Caching:
- Behavior: After the initial lookup, VPC details are cached in
cdk.context.json. - Action: If the VPC's configuration changes, reset the cache using the
--resetflag to perform a fresh lookup.
- Behavior: After the initial lookup, VPC details are cached in
-
Cache Reset Procedure:
npx aws-cdk context --reset CONTEXT_NUMBER_OR_KEY # Alternatively: cdk context --reset CONTEXT_NUMBER_OR_KEYReplace
CONTEXT_NUMBER_OR_KEYwith the appropriate identifier from thecdk.context.jsonfile.
Troubleshooting VPC lookups
| Symptom | What to check |
|---|---|
| Account or region is not specified | Set concrete env.account and env.region on the stack; a deploy-time token cannot identify a synth-time lookup target |
| No matching VPC | Check the VPC ID, CLI identity, region, and permissions used for the lookup |
| Multiple matching VPCs | Prefer vpcId, or tighten the name/tag filters |
| Old subnet information | Reset only the relevant VPC context key, synthesize again, and review the diff |
| No private subnets found | Inspect the existing subnet types and select a group that actually exists |
Commit cdk.context.json with your infrastructure source so other environments use the reviewed lookup values. AWS explains the caching and reset workflow in Context values and the AWS CDK.
Choose subnets and use the imported VPC
VPC lookup and subnet selection are separate decisions. Before placing a workload, follow subnet selection in AWS CDK and check its routing requirements. A Lambda function does not gain a public IP or internet access merely by being placed in a public subnet.
For a complete database and client example, continue with RDS PostgreSQL and EC2 using AWS CDK. That guide creates a new VPC; substitute this imported VPC only after verifying that its subnets and security boundaries meet the example's requirements.
Quick Recap
How do you import an existing VPC into AWS CDK?
Use ec2.Vpc.fromLookup() with an identifying option such as vpcName, vpcId, tags, or isDefault, after explicitly setting the stack's account and region so CDK can perform the lookup.
What lookup options does Vpc.fromLookup support?
You can look up a VPC by name (vpcName), by ID (vpcId), by tags (key/value pairs), or by marking isDefault: true to import the account's default VPC.
Why does CDK need an explicit account and region to import a VPC?
fromLookup performs an actual AWS API lookup at synth time, and CDK needs to know exactly which account and region to query to locate the correct VPC.
How do you refresh cached VPC lookup values if the VPC changes?
Run cdk context to find the cache key, then cdk context --reset KEY_OR_NUMBER to clear it, and run cdk synth again to force a fresh lookup.
Can you modify an imported VPC with CDK?
fromLookup references the VPC without transferring ownership of its existing resources to the stack. You can create new resources in that VPC, but changes to its existing network configuration belong in the stack or process that owns it.
Comments
Share your thoughts and questions below