ComputedWhen Alternatives - Computed value dependencies

Every time when I need of a dependency, not work correctly.

Imagine if I have one resource

resource "resource" "redis" {
    is_public      = true

He has an output port.
Every time when I change is public, your port change.

But now I have other resource if depende of this, but in the other resource, when I change port, not is identified, he change only when I apply 2 times in sequence.

Hi @themarkwill :wave: Welcome to HashiCorp Discuss and thank you for reaching out about this.

From your post title, I presume you are asking about functionality similar to helper/schema.Schema type ComputedWhen field (which for other readers is deprecated / not actually implemented, but left for code compatibility). This was supposed to automatically modify the plan value for the current attribute to be an unknown (known after apply) value when the referenced attribute values changed. In Terraform, if a plan value is not set to unknown, then Terraform assumes its value is not changing for other references to that value, which is why it takes two applies to pick up the change.

For terraform-plugin-sdk based providers, it is possible to modify the plan to accomplish this with helper/schema.Resource type CustomizeDiff field. Working with CustomizeDiff is generally an advanced use case as it has some undesirable behaviors in terraform-plugin-sdk, but for this particular use case, it generally works as expected. There are some helpers in the helper/customdiff package for simplifying CustomizeDiff implementations. Note that terraform-plugin-sdk sometimes overloads the term “computed” for unknown values.

Something like the below should get you close:

  // ... other fields ...
  CustomizeDiff: customdiff.All(
    customdiff.ComputedIf("port", func(_ context.Context, diff *schema.ResourceDiff, _ interface{}) bool {
      return diff.HasChange("is_public")

For terraform-plugin-framework based providers, this can be accomplished via its plan modification support. Generally for cases like these, its easier via a schema-based plan modifier.

Hope this helps!

1 Like