How to use an "each.value" when referencing another resource

I’m very new to Terraform so this may be trivial. Is it possible to reference another resource by using data from a CSV file?


resource "aci_cdp_interface_policy" "cdp_enable" {
  name        = "CDP_Enabled"
  admin_st    = "enabled"
  annotation  = "none"

resource "aci_cdp_interface_policy" "cdp_disable" {
  name        = "CDP_Disabled"
  admin_st    = "disabled"
  annotation  = "none"

# Access Port Policy Group Resources
resource "aci_leaf_access_port_policy_group" "ap_pg_prod"{
  for_each                        = { for pg in local.acc_int_pg : pg.IPG-NAME => pg }
  name                            = each.value.IPG-NAME
  relation_infra_rs_cdp_if_pol    = "aci_cdp_interface_policy.${each.value.CDP-POL}".id #LINE 197

I’m getting the following after terraform plan is run:

Error: Unsupported attribute

│ on line 197, in resource “aci_leaf_access_port_policy_group” “ap_pg_prod”:
│ 197: relation_infra_rs_cdp_if_pol = “aci_cdp_interface_policy.${each.value.CDP-POL}”.id

│ Can’t access attributes on a primitive-typed value (string).

Hi - Welcome to the forum - please reformat your message

Terraform does not have support for dynamically referencing arbitrary other resource blocks. All references to blocks have to be explicitly written into the configuration file.

There are two common workarounds.

Option 1: Restructure the group of resource blocks that you want to reference, to one resource block with a for_each. Whilst you can’t dynamically reference a different resource block, you can dynamically specific which element of a for_each you want to refer to.

Option 2: Write out a local variable consisting of an object/map that map strings to various other resource blocks. Do your lookup through your separately curated lookup variable.

Thanks! I’ll give this a shot and post back when/if I figure it out.