Terraform language includes a number of built-in functions that you can call from within expressions to transform and combine values

Check the following for examples


Functions

Terraform also have an interactive console, to get into the console type terraform console which also loads the state associated with the configuration directory by default, allowing us to load any values that is currently stored in. Also loads variables that are stored in the configuration file. In the console, you can also use mathematic operations and conditional expressions

There are the following function types:

Dynamic Block

Dynamic Blocks in Terraform let you repeat configuration blocks inside a resource, provider, provisioned, or data source based on a variable, local, or expression you use inside them which helps you keep your code clean and following the DRY method

Dynamic block help to create repeatable nested blocks within a resource which is similar to the for expression

Example

Without dynamic block

resource "azurerm_virtual_network" "dynamic_block" {
  name                = "vnet-dynamicblock-example-centralus"
  resource_group_name = azurerm_resource_group.dynamic_block.name
  location            = azurerm_resource_group.dynamic_block.location
  address_space       = ["10.10.0.0/16"]

  subnet {
    name           = "snet1"
    address_prefix = "10.10.1.0/24"
  }

  subnet {
    name           = "snet2"
    address_prefix = "10.10.2.0/24"
  }

  subnet {
    name           = "snet3"
    address_prefix = "10.10.3.0/24"
  }

  subnet {
    name           = "snet4"
    address_prefix = "10.10.4.0/24"
  }
}

With dynamic block

resource "azurerm_virtual_network" "dynamic_block" {
  name                = "vnet-dynamicblock-example-centralus"
  resource_group_name = azurerm_resource_group.dynamic_block.name
  location            = azurerm_resource_group.dynamic_block.location
  address_space       = ["10.10.0.0/16"]

  dynamic "subnet" {
    for_each = var.subnets
    iterator = item   #optional
    content {
      name           = item.value.name
      address_prefix = item.value.address_prefix
    }
  }
}

// the subnets var
variable "subnets" {
  description = "list of values to assign to subnets"
  type = list(object({
    name           = string
    address_prefix = string
  }))
}

Expressions