Referencing existing resources in Terraform-CDK

Hi!

I’m just getting started and was wondering if it’s possible to reference existing AWS resources with cdktf.

I’m using Python and could easily lookup resources with boto3, but I think it would be helpful if cdktf supported lookups of existing resources itself. For instance, let’s say I’m creating an RDS cluster - I need to pass in subnets, security groups, etc - most of which I already have created. It would be nice to look those up dynamically using cdktf itself - I think it would also help learn the API.

But perhaps terraform outputs are the intended pattern.

Oh, the DataAwsXXX classes pull directly from AWS? I was thinking they read from remote Terraform state. Seems like I’m close with this, but I haven’t yet figured out why I get a unique ID and the stack/app name in the lookup instead of the existing resource I’m looking for.

    r = DataAwsRdsCluster(self, id='mycluster', cluster_identifier='mycluster')

Trying to apply this example to Python:

region = DataAwsRegion(self, ‘current’)

Then region.name is:

‘${data.aws_region.example10_current_118BF5AE.name}’

The “Data” classes are what you want to use.

‘${data.aws_region.example10_current_118BF5AE.name}’

is expected. When the Terraform cli runs (what happens when you do cdktf deploy), that value is treated as a lookup. If you pass it to another resource, the lookup is evaluated and you’ll get the expected value passed in.

With the way CDK for Terraform currently works those lookups aren’t available to the logic you are writing directly, only as pass-throughs to other resources and (eventually) functions.

Thanks for the response! I also realized it works the way you explained it and had intended to come back and comment, but you beat me to it!

Really looking forward to experimenting more!

Related to this topic, is it possible to use data from terraform_remote_state with cdktf? Here’s a pattern that I’d like to reproduce (to use existing data):

data terraform_remote_state my_remote_state {
  backend = "s3"
  config = {
    bucket  = "mybucket"
    encrypt = true
    key     = "mykey"
    region  = "us-east-1"
  }
}

locals {
  private_subnet_ids = data.terraform_remote_state.my_remote_state.outputs.private_subnet_ids
}

Remote state is not supported as construct at the moment, but totally doable via escape hatches - https://cdk.tf/escape-hatch - There’s an issue to tackle this as well https://cdk.tf/issues/33

Thank you so much for the awesome project and your help here!

2 Likes