In AWS CDK, the equivalent of Terraform data source are CDK Lookup functions and methods. These allow you to query existing AWS resources and their properties. Here are some common ways to lookup existing resources in AWS CDK:
// Look up an existing VPC
const vpc = ec2.Vpc.fromLookup(this, 'ExistingVPC', {
vpcId: 'vpc-xxxxxx' // or
isDefault: true // to look up the default VPC
});
// Look up an existing security group
const securityGroup = ec2.SecurityGroup.fromSecurityGroupId(
this, 'ExistingSG', 'sg-xxxxxx'
);
// Look up an existing subnet
const subnet = ec2.Subnet.fromSubnetId(
this, 'ExistingSubnet', 'subnet-xxxxxx'
);
// Look up the latest Amazon Linux 2 AMI
const ami = new ec2.AmazonLinuxImage({
generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
});
// Or lookup a specific AMI
const specificAmi = ec2.MachineImage.lookup({
name: 'ami-name-pattern-*',
owners: ['amazon']
});
// Look up an existing certificate
const certificate = acm.Certificate.fromCertificateArn(
this, 'ExistingCert',
'arn:aws:acm:region:account:certificate/xxx'
);
// Look up an existing S3 bucket
const bucket = s3.Bucket.fromBucketName(
this, 'ExistingBucket', 'my-bucket-name'
);
// Look up an existing IAM role
const role = iam.Role.fromRoleArn(
this, 'ExistingRole',
'arn:aws:iam::account:role/role-name'
);
// Custom resource for looking up specific AWS resource attributes
const customResource = new CustomResource(this, 'CustomLookup', {
serviceToken: myLambdaFunction.functionArn,
properties: {
// properties needed for the lookup
}
});
// For more complex scenarios, you can use the AWS SDK in a Custom Resource
import * as aws from 'aws-sdk';
const myLookup = new lambda.Function(this, 'LookupFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromInline(`
const AWS = require('aws-sdk');
exports.handler = async (event) => {
// Use AWS SDK to look up resources
};
`)
});