[Beginnner] define required attribute based on other attributes value

Hello HashiCorp community,

I was wondering if it is possible to define a schema definition where I can require an attribute once a specific value of another attribute is set.

resource "a_resource" "my_resource" {
  kind  = "kind_that_does_requires_value"
  value = "test" // required
}

resource "a_resource" "my_resource" {
  kind  = "kind_that_does_not_requires_value"
}

I found the RequiredWith option, but this is only based on an attribute and does not take into account the value of the attribute as far as I am aware. Is there a way for me to enforce/hint this in the schema definition?

i guess attribute validation can help here https://developer.hashicorp.com/terraform/plugin/framework/validation

1 Like

Thanks, I can see this is documented in the new Framework SDK using path expressions.

I forgot to mention that the Provider I am using is still using SDKv2. I can see this is somewhat possible in runtime (https://github.com/hashicorp/terraform-plugin-sdk/issues/233), not so much at the Schema definition.

Thanks for your time!

Provider resources written with terraform-plugin-sdk can use CustomizeDiff functionality to perform this type of validation to return errors during planning. For example, hashicorp/terraform-provider-aws uses this type of approach in its code here: terraform-provider-aws/ebs_volume.go at 16873dd05f9da841c6d9a2045eae253b256f328d · hashicorp/terraform-provider-aws · GitHub

1 Like