Search code examples
azureterraformterraform-provider-azure

How to use depends_on in terraform if resources are created using count or for_each


Hello How to use depends_on in the cases of count or for_each.

The basic syntax of depends_on assumes

resource "azurerm_storage_container" "cont1"{
.....
.....
depends_on = [
    azurerm_storage_account.storageAccount
 ]
}
 
resource "azurerm_storage_account" "storageAccount" {
  count                   = 3
  name                    = "storageAccountName-${count.index}"
  resource_group_name     = "rg-demo"
  location                = "centralus"
  account_tier            = "Standard"
  account_replication_type= "LRS"
  # all other relevant attributes
}

So here its azurerm_storage_account.storageAccount if only one such resource were to be created but if we have many azurerm_storage_account created as for_each or count was used in them then what to write in place of storageAccount? Like suppose we have to have a dependency of storageAccountName-2 on the container then how will we write the depends on?


Solution

  • As was mentioned in a comment above, you can add an index to the storageAccount resource reference:

    resource "azurerm_storage_account" "test_storage_account" {
      count                    = 3
      name                     = "teststorageaccount${count.index}"
      ...
    }
    
    resource "azurerm_storage_container" "container" {
      depends_on = [
        azurerm_storage_account.test_storage_account[0]
      ]
      name                  = "testcontainer"
      ...
    }
    

    You can also omit the index and have the container(s) depend on the entire storage account resource. Both worked in my testing.

    Additionally, while implicit dependency would normally allow you to not have a "depends_on" block in the container resource (if you had a single storage account), the implicit dependency does not appear to work when you have multiple storage accounts created with a "for_each" that are later referenced in a storage container resource.