Let’s create a conditional resource in Terraform based on a mapped key. Following post used for reference:
https://medium.com/@business_99069/terraform-conditional-resources-based-on-a-map-key-a37fd329d3a1
Start with a map data structure in our variable.tfvars
:
docker_swarm = {
az-ds-man-tst1 = {
ip_address = "172.19.100.82"
environment = "test"
application = "docker"
docker_role = "swarm-manager"
vm_size = "Standard_B2s"
storage_account_type = "Standard_LRS"
os_disk_storage_account_type = "Standard_LRS"
},
az-ds-man-tst2 = {
ip_address = "172.19.100.83"
environment = "test"
application = "docker"
docker_role = "swarm-manager"
vm_size = "Standard_B2s"
storage_account_type = "Standard_LRS"
os_disk_storage_account_type = "Standard_LRS"
},
az-ds-man-tst3 = {
ip_address = "172.19.100.84"
environment = "test"
application = "docker"
docker_role = "swarm-manager"
vm_size = "Standard_B2s"
storage_account_type = "Standard_LRS"
os_disk_storage_account_type = "Standard_LRS"
},
az-ds-wrk-tst1 = {
ip_address = "172.19.100.85"
environment = "test"
application = "docker"
docker_role = "swarm-worker"
vm_size = "Standard_A2_v2"
storage_account_type = "StandardSSD_LRS"
os_disk_storage_account_type = "Standard_LRS"
},
az-ds-wrk-tst2 = {
ip_address = "172.19.100.86"
environment = "test"
application = "docker"
docker_role = "swarm-worker"
vm_size = "Standard_A2_v2"
storage_account_type = "StandardSSD_LRS"
os_disk_storage_account_type = "Standard_LRS"
}
az-ds-wrk-tst3 = {
ip_address = "172.19.100.87"
environment = "test"
application = "docker"
docker_role = "swarm-worker"
vm_size = "Standard_A2_v2"
storage_account_type = "StandardSSD_LRS"
os_disk_storage_account_type = "Standard_LRS"
}
az-ds-wrk-tst4 = {
ip_address = "172.19.100.88"
environment = "test"
application = "docker"
docker_role = "swarm-worker"
vm_size = "Standard_A2_v2"
storage_account_type = "StandardSSD_LRS"
os_disk_storage_account_type = "Standard_LRS"
}
}
Create a conditional azurerm_network_interface_backend_address_pool_assocation resource based on the value of the “docker_role” key in the above map. The lookup used in the logic below will only return true if the value is “swam-worker”. This resource block can be placed in any terraform file within the project.
resource "azurerm_network_interface_backend_address_pool_association" "ds-swarm-workers" {
for_each = {
for k in keys(var.docker_swarm) : //loop over each object in docker_swarm map
k => var.docker_swarm[k] //assign value of k to docker_swarm object with key value
if lookup(var.docker_swarm[k], "docker_role", "swarm-worker") == "swarm-worker" //if docker_role attirbute is set to swarm worker, return true
}
network_interface_id = azurerm_network_interface.dswarm[each.key].id
ip_configuration_name = "internal"
backend_address_pool_id = azurerm_lb_backend_address_pool.ds-swarm-workers.id
}