conditional-statementsterraform-provider-azureazure-rm

Trying to use terraform if/else statement on a block in terraform


I am new to terraform and stuck on something I think can be done but don't know. I am trying to see if there is a way to make the delegation block in azure subnet optional from an if/else. I tried to do it off of a variable but keep getting an error.

#variable: 

variable "resource_group_name" {
  type        = string
  description = "name of rg v-net is located"
}

variable "subnet_name" {
  type        = string
  description = "name of subnet"
}

variable "subnet_address_prefixes" {
  type        = list(string)
  description = "address space of subnet"
}

variable "service_endpoints" {
  type        = list(string)
  default     = null
  description = "Service enpoints connected to subnet or vm"

}

variable "vnet_name" {
  type        = string
  description = "name of vnet"
}

variable "delegation_name" {
  type    = string
  default = ""
}
variable "service_delegation" {
  type = object({
    name   =  string
    action =  list(string)

  })
  default = {
    name   = "Microsoft.DBforMySQL/flexibleServers"
    action = []
  }
}
#module 

resource "azurerm_subnet" "panynj_subnet" {
  name                 = var.subnet_name
  resource_group_name  = var.resource_group_name
  virtual_network_name = var.vnet_name
  address_prefixes     = var.subnet_address_prefixes
  service_endpoints    = var.service_endpoints
    delegation {
    name = var.delegation

    service_delegation {
      name    = var.service_delegation.name
      actions = var.service_delegation.action
    }
}

I tried to apply the if else statement to the variable but that doesn't seem to work and I don't know if it can be done in a dynamic block.


Solution

  • Usually, a dynamic block along with a for_each that runs 0 or 1 times is used to make a block optional.

    Let's assume that "delegation" should be added only when var.delegation_name is not blank.

      # your code here
    
      dynamic "delegation" {
        for_each = var.delegation_name != "" ? [1] : []
        content {
          name = var.delegation_name
    
          service_delegation {
            name    = var.service_delegation.name
            actions = var.service_delegation.action
          }
        }
      }