CDK interogate resources

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:

VPC Lookup

// Look up an existing VPC
const vpc = ec2.Vpc.fromLookup(this, 'ExistingVPC', {
  vpcId: 'vpc-xxxxxx' // or
  isDefault: true // to look up the default VPC
});

Security Group Lookup

// Look up an existing security group
const securityGroup = ec2.SecurityGroup.fromSecurityGroupId(
  this, 'ExistingSG', 'sg-xxxxxx'
);

Subnet Lookup

// Look up an existing subnet
const subnet = ec2.Subnet.fromSubnetId(
  this, 'ExistingSubnet', 'subnet-xxxxxx'
);

AMI Lookup

// 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']
});

Certificate Lookup

// Look up an existing certificate
const certificate = acm.Certificate.fromCertificateArn(
  this, 'ExistingCert', 
  'arn:aws:acm:region:account:certificate/xxx'
);

S3 Bucket Lookup

// Look up an existing S3 bucket
const bucket = s3.Bucket.fromBucketName(
  this, 'ExistingBucket', 'my-bucket-name'
);

IAM Role Lookup

// Look up an existing IAM role
const role = iam.Role.fromRoleArn(
  this, 'ExistingRole',
  'arn:aws:iam::account:role/role-name'
);

Using Custom Resource for more comples lookups

// Custom resource for looking up specific AWS resource attributes
const customResource = new CustomResource(this, 'CustomLookup', {
  serviceToken: myLambdaFunction.functionArn,
  properties: {
    // properties needed for the lookup
  }
});

Using AWS SDK directly

// 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
    };
  `)
});