How to conditionally use different arguments

I’m trying to create and azurerm_private_endpoint resource. This resource has a mandatory “private_service_connection” block, and that block requires either a “private_connection_resource_id” argument or a “private_connection_resource_alias” argument, but not both. One of them is mandatory.

How do I make a terraform resource that uses some sort of if statement or conditional or dynamic or something like that to decide which argument to use based on a boolean variable? I know how to do that for values, but not for the arguments themselves and I can’t find any help on this.

This is the pseudocode for what I want:

private_service_connection {
name = “blah”
if “var.use_id” = “true”:
private_connection_resource_id = “myid”
else:
private_connection_resource_alias = “myalias”
}

so the final, applied block would be one of these two possible blocks, depending on the value of var.use_id:

private_service_connection {
name = “blah”
private_connection_resource_id = “myid”
}

private_service_connection {
name = “blah”
private_connection_resource_alias = “myalias”
}

Does this achieve your aim?

private_service_connection {
  name = "blah"
  private_connection_resource_id = var.use_id ? "myid" : null
  private_connection_resource_alias = var.use_id == false ? "myalias" : null
}

This is what I would’ve suggested too.

One caveat with this technique: if the provider itself is enforcing that only one of these can be set, sometimes providers don’t properly handle the case where Terraform doesn’t yet know whether the value is null (what appears in a plan as (known after apply).

If this provider has that quirk then you will need to make sure that var.use_id is a value set directly in your configuration, rather than something derived indirectly from data Terraform will only learn during the apply phase.

(Over time providers are getting better at handling this with the help of newer SDK / framework features, so I’m not sure if this still matters for these arguments in particular.)

1 Like