mardi 26 janvier 2021

Terraform, (AzureRM) Can you have if, else, else (conditional situations) for resource deployments?

I am using Azure DevOps with Terraform to deploy multiple environments within my subscriptions and I am leveraging the same main.tf, variables.tf, and tfvars for all my environments (3 environments in total). Within the tf files and tfvars file, I am passing in DevOps variables within Variable Groups (Azure DevOps specific) to identify different variables and values. Say for example, I want to build 3 different subnets with the same resource (1 in each subscription):

Main.tf:

resource "azurerm_subnet" ""example" { 
  for_each             = var.is_env_one ? var.subnet_range_one : var.subnet_range_two : var.subnet_range_three
  resource_group_name  = azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.example.name

  name                 = each.value["name"]
  address_prefixes     = each.value["address_prefixes"]
}

Variables.tf:

variable "is_env_one" {
  description = "Boolean on if this is environment 1 or not"
  default = true 
}
variable "is_env_two" {
  description = "Boolean on if this is environment 2 or not"
  default = true 
}
variable "is_env_three" {
  description = "Boolean on if this is environment 3 or not"
  default = true 
}
variable "subnet_range_one" {
  description = "tfvars file will dictate # of subnets and values"
}
variable "subnet_range_two" {
  description = "tfvars file will dictate # of subnets and values"
}
variable "subnet_range_three" {
  description = "tfvars file will dictate # of subnets and values"
}

tfvars information (example of 1 of the ranges configs):

subnet_range_one = {
  subnet_1 = {
    name             = "{[_subnet-devops-name_]}" #Azure DevOps Variable that dictates the value
    address_prefixes = "{[_subnet-devops-address-prefix_]}" #Azure DevOps Variable that dictates the value
  }
}

Is there a way for me to write my code to differentiate between the environments using DevOps variables? Aka, can I use a conditional format to say either pick a, b or c three options)?

Aucun commentaire:

Enregistrer un commentaire