Terraform cdktf for reference for variable to other resource or from resource to other resource

new SecurityGroup(this,“sec1grp”,{

  name: "security1",

  vpcId:"vpcs",  

  ingress:[{

    fromPort: 22 ,

    toPort:  65535 , 

    cidrBlocks: [ "41.79.199.44/32"], 

    protocol: "tcp"

  },

  {

    fromPort: 80  ,

    toPort:  65535 , 

    cidrBlocks: [ "0.0.0.0/0"], 

    protocol: "tcp"

  },

  {

    fromPort: 443  ,

    toPort:  65535 , 

    cidrBlocks: [ "0.0.0.0/0"], 

    protocol: "tcp"  

  },

  {

    fromPort: 5432 ,

    toPort:  65535 , 

    cidrBlocks: [ "0.0.0.0/0"], 

    protocol: "tcp"

  }],

  egress:[{

    fromPort: 0 , 

    toPort: 0 ,  

    cidrBlocks: [ "0.0.0.0/0"], 

    protocol: "-1"

  }]

}

)

new TerraformVariable(this,“ports”,{

  type:"list", 

  default: [ 22  , 80 , 443  ,5432 ]

})

new TerraformOutput(this, “portsout” .{

   value: "ports"

 })

terraform cdktf how to reference variable to resource for similier to terraform var,ports for related typescript and reference resource id to other resource for example vpc_id

Hi @mohammedbanabila

I’m not sure whether I understand your question correctly, so please tell me if I understand you right:

You want to pass a Terraform variable with a list of ports to the stack and want to use that list in the security group to allow ingress to those ports?

– Ansgar

yes and this what i want to do

Hey @mohammedbanabila,
for this currently overrides are required but we’re working on the Token system to improve such things in the future.

It should work with something like this:

const ports = new TerraformVariable(this, "ports", {
  type: "list",
  default: [22, 80, 443, 5432],
});

const sg = new SecurityGroup(this, "sec1grp", {
  name: "security1",
  vpcId: "vpcs",
  egress: [
    {
      fromPort: 0,
      toPort: 0,
      cidrBlocks: ["0.0.0.0/0"],
      protocol: "-1",
    },
  ],
});
sg.addOverride("dynamic.ingress", {
  for_each: ports.listValue,
  content: {
    fromPort: "${ingress.value}",
    toPort: "${ingress.value}",
    cidrBlocks: ["0.0.0.0/0"],
    protocol: "-1",
  },
});

new TerraformOutput(this, "portsout", {
  value: ports.listValue,
});

Please note: Different to your code I changed the toPort to the same value as the fromPort as that denotes a range and having the same value (e.g. 80) for both will only open that single port.