Create resources conditionally without using count

A well known technique to control the conditional creation of resources is to use something like:

count = var.create_resource ? 1 : 0

and I tried this with the Azure provider on resources such as:

resource "azuread_service_principal_password" "auth" {
  service_principal_id = azuread_service_principal.auth.id
  value                = random_string.password.result
  end_date_relative    = "240h"
}

The problem with this is that because there is no for_each loop involved terraform plan instructed me to use an index on (for example) value = random_string.password.result, the problem being that this does not like an index. My question is therefore this, how can I achieve the same result as using count but without using count.

Hi @chrisadkin ,
as per my understanding you’d like to create >=0 resources of type azuread_service_principal_password and also use unique random_string.passwords for those.
In principal you can use the same count or for_each iterator on both resources, so creating equal number of resources.

What I would like to do is create a service principle and the other resources associated with it if a variable is set to true, otherwise don’t create it at all.

Isn’t the variable (true, count) also applicable to all resources which could be conditional?

As you say the count = var.create_resource ? 1 : 0 mechanism is very common to conditionally create a resource. You would just add that count to whichever resources you want to be conditional.

As those resources now have a count you need to ensure any references to them now use an index value.

So for example

resource "azuread_service_principal_password" "auth" {
  count = var.create_resource ? 1 : 0

  service_principal_id = azuread_service_principal.auth.id
  value                = random_string.password.result
  end_date_relative    = "240h"
}

Would now be referenced as azuread_service_principal_password.auth[0].whatever if the resource is enabled. You need to take account of the possibility that is isn’t enabled, for example using a condition check: variable = var.create_resource ? azuread_service_principal_password.auth[0].whatever : ""

Taking a step back, what I need to do is to restructure my code in order to use modules.

1 Like