How to Import Existing Resources in AWS CDK


Borislav Hadzhiev

Sat Apr 24 20212 min read


Photo by Lucas Wesney

Updated on Sat Apr 24 2021

Importing Existing Resources in CDK #

In order to import existing resources in CDK we have to use the static fromResource* methods on the resource's construct, for instance:

As a general rule of thumb, we use the fromResourceName and fromResourceArn methods unless we don't have access to the name or ARN of the resource, in which case we use the fromResourceAttributes method.

The code for this article is available on GitHub

To import an existing bucket by name into a CDK stack we can use the fromBucketName static method:

const existingBucketFromName = s3.Bucket.fromBucketName( this, 'bucket-from-name-id', 'YOUR_BUCKET_NAME', ); console.log('existingBucketFromName ๐Ÿ‘‰ ', existingBucketFromName.bucketName);

If I now execute the cdk synth command we can see that the value is resolved at synthesis time:

existing bucket name

To import an existing bucket by ARN we can use the fromBucketArn static method:

const existingBucketFromArn = s3.Bucket.fromBucketArn( this, 'bucket-from-arn-id', 'YOUR_BUCKET_ARN', );

And to import an existing bucket from Attributes, we use the fromBucketAttributes static method:

const existingBucketFromAttributes = s3.Bucket.fromBucketAttributes( this, 'bucket-from-attributes-id', { region: 'us-east-1', bucketArn: 'arn:aws:s3:::YOUR_BUCKET_NAME', }, );

All of the above methods resolve at synthesis time.

Most Level 2 Constructs implement at least 2 of the 3 fromResource* methods.

For example, to import an existing Dynamodb table by name, we have to use the fromTableName static method:

const existingTableFromName = dynamodb.Table.fromTableName( this, 'table-from-name-id', 'YOUR_TABLE_NAME', ); console.log('existingTableFromName ๐Ÿ‘‰ ', existingTableFromName.tableName);

The value again resolves at synthesis time:

existing table name

To import an existing table from ARN we have to use the fromFunctionArn static method:

const existingTableFromArn = dynamodb.Table.fromTableArn('YOUR_TABLE_ARN');

And to import an existing table from attributes we have to use the fromTableAttributes static method:

const existingTableFromAttributes = dynamodb.Table.fromTableAttributes( this, 'table-from-attributes-id', { tableName: 'YOUR_TABLE_NAME', }, );

It's quite repetitive once we know what the naming convention of the methods is.

Most of the time we end up using the fromResourceName and fromResourceArn methods, and resort to using fromResourceAttributes when we don't have the name or the ARN of the resource.

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee