Search code examples
azureterraformterraform-provider-azureterraform-template-file

Terraform how to create a block of code based on a conditions


I'm trying to create a resource with a creation condition for the github_configuration block, but I don't find such an option. Depending on the environment I need or don't need git config. I can't figure out how I can set up such a dependency

resource "azurerm_data_factory" "myDataFactory" {
  name                = var.datafactortyName
  location            = azurerm_resource_group.myResourceGroup.location
  resource_group_name = azurerm_resource_group.myResourceGroup.name

  dynamic "github_configuration" {
  #count = var.Environment == "dev" ? 1 : 0
  for_each = var.Environment == "dev"

    content {
      account_name    = var.Environment == "dev" ? var.AccountName : null
      branch_name     = var.Environment == "dev" ? var.Branch : null
      git_url         = var.Environment == "dev" ? var.RepoUrl : null
      repository_name = var.Environment == "dev" ? var.RepoName : null
      root_folder     = var.Environment == "dev" ? var.RepoFolder : null
    }
  }
}

Solution

  • To make github_configuration block optional, you can do:

      dynamic "github_configuration" {
    
        for_each = var.Environment == "dev" ? [1] : []
    
        content {
          account_name    = var.Environment == "dev" ? var.AccountName : null
          branch_name     = var.Environment == "dev" ? var.Branch : null
          git_url         = var.Environment == "dev" ? var.RepoUrl : null
          repository_name = var.Environment == "dev" ? var.RepoName : null
          root_folder     = var.Environment == "dev" ? var.RepoFolder : null
        }
      }
    }
    

    [1] ensures that for_each executes ones. Actual value of 1 is irrelevant. It can be any value, as long as the list have one element.