Referencing resource instance from other instance of the same resource

I’m trying to create terraform resource containing reference to the other instance of the same resource. During terraform plan I get exception there there is a cycle dependency between resources. Does terraform support this approach ? Code looks like this:

resource "schemaregistry_schema" "domain_model" {
  for_each = {for schema in var.schemas: schema.qualifiedTypeName => schema }

  subject = each.value.qualifiedTypeName
  schema = each.value.content

  dynamic "reference" {
    for_each = each.value.dependencies
    content {
      name = reference.value
      subject = schemaregistry_schema.domain_model[reference.value].subject
      version = schemaregistry_schema.domain_model[reference.value].version
    }
  }
}

Hi @tomekb,

In Terraform dependencies are between resource blocks as a whole, rather than between individual instances of a resource, because the for_each expression itself can create dependencies and so Terraform must build the dependency graph before evaluating that expression.

I’m not familiar with this provider you are using but it seems like this system unfortunately isn’t really amenable to being described dynamically in Terraform like this, because Terraform resolves the dependency graph statically before evaluation but yet your data structure var.schema seems to itself represent a graph that Terraform would need to process dynamically.

I think in this case the only way to represent this with Terraform would be to represent the graph directly in the Terraform language, writing out separate resource "schemaregistry_schema" blocks for each of your schemas and using simple Terraform references to populate the reference blocks inside.

A compromise could be to write a separate program to generate separate resource blocks with dependencies based on your source data. You could use the JSON variant of the Terraform language to represent that, in case that makes it easier to generate from code written in a language which already has a JSON encoding function.

Thanks,
I’ve decided to generate resource blocks based on metadata.