Using Conditional Expressions in Terraform

Viewed 46

I heard that terraform doesn't support if else condition. I would like to know what is the alternative for if/else condition in that case when using terraform. I have the below piece of code which by default sets up the below 2 Rules on all the Network Security Group (i.e say around 20+ NSG Groups).

Now, for a specific Network Security Group (i.e nsg-restricted-jdmsg-chn), I wanted to adjust this default rule slightly.. I wanted to change the rdp port from 3389 to 33091 and for the second rule, I wanted to change the ssh port from 22 to 26.

How can we accomplish this condition rule in terraform?

resource "azurerm_network_security_rule" "testrules" {
  for_each                    = local.nsgrules
  resource_group_name         = var.jdgrp.rg.name
  location                    = var.jdgrp.rg.location
  name                        = nsg-restricted-${var.cfg.name}"
  security_rule {
    name                        = rdp
    direction                   = "Inbound"
    access                      = "Allow"
    priority                    = "100"
    protocol                    = "Tcp"
    source_port_range           = "*"
    destination_port_range      = 3389
    source_address_prefix       = "VirtualNetwork"
    destination_address_prefix  = "192.168.2.0/24"
  }
  security_rule {
    name                        = ssh
    direction                   = Inbound
    access                      = "Allow"
    priority                    = "101"
    protocol                    = "Tcp"
    source_port_range           = "*"
    destination_port_range      = "22"
    source_address_prefix       = "VirtualNetwork"
    destination_address_prefix  = "192.168.2.0/24"
  }
}

Additional Info

The value for name = nsg-restricted-${var.cfg.name}" is getting it from the below code.

jd-tech.tf

module "jd-tech" {
  for_each = {
    "${local.jd-tech_rst.name" = local.jd-tech_rst
    "${local.jd-tech_dct.name" = local.jd-tech_dct
    "${local.jd-tech_rpr.name" = local.jd-tech_rpr
    "${local.jd-tech_amb.name" = local.jd-tech_amb
     ...
     ...
     }
  source = "./jd-tech"
  ...
  ...
  cfg    = each.value
  ...
}
1 Answers

The easiest way to do this would be by using the conditional expresion (you probably know it as ternary operator from other programming languages) [1]. To achieve what you want, you just need to do this for RDP:

destination_port_range = local.jd-tech_chn.name == "nsg-restricted-jdmsg-chn" ? 33091 : 3389

And for SSH:

destination_port_range = local.jd-tech_chn.name == "nsg-restricted-jdmsg-chn" ? 26 : 22

You would have to define either a local variable or a regular one. In my answer it is a regular variable.


[1] https://www.terraform.io/language/expressions/conditionals#conditional-expressions

Related