Hi,
Here is what I have got:
- Module 1: gerenate load balancer and its related resources, AND also call module 2 to generate VMs
- Module 2: generate network interface and VMs
- Template,
main.tf to call module 1 to provision Azure resources
File tree:
Terraform
-Modules
+ Module 1
++ main.tf
++ outputs.tf
++ variables.tf
+Module 2
++ (same as M1)
- Tempaltes
+ template 1
++ (same as M1)
Since I manage all the variables from
variables.tf files associated with each modules and each template and some variables are the same across different places, I have been struggling with managing variables and make sure they are the same across different
variables.tf files. Additionally, I run Terraform via CI/CD pipeline in Azure DevOps. I have set .tfvars to take all variables from the pipeline and pass them in the terraform files.
My .tfvars looks like this, tokens will be replaced by pipeline variables in the run time
# test.tfvars
prefix = "__prefix__"
location = "__location__"
image_name = "__image_name__"
number_of_instances = "__number_of_instances__"
The issue:
I pass variable number_of_instances as a count (for example, I pass number_of_instances = 2 here getting the value from the pipeline variable) into module 1 to generate 2 load balancer nat rules, and then pass lb_nat_rule_ids to module 2. I dont know how to pass the array of ids to module 2 as variables, so that module 2 can resolve and get the id.
#module1
...
resource "azurerm_lb_nat_rule" "tcp" {
resource_group_name = "${var.resource_group_name}"
name = "RDP-VM-${count.index}"
protocol = "tcp"
frontend_port = "5000${count.index + 1}"
backend_port = 3389
frontend_ip_configuration_name = "LoadBalancerFrontEnd"
count = "${local.number_of_instances}"
}
module "azure-vm" {
source = "../../modules/azure-vm"
resource_group_name = "${var.resource_group_name}"
...
# how to get array of azurerm_lb_nat_rule id here ??
# Is this the right way to get all azurerm_lb_nat_rule ids
nat_rule_ids = "${azurerm_lb_nat_rule.tcp.*.id}"
}
#Module2
...
resource "azurerm_network_interface_nat_rule_association" "nat_rule" {
network_interface_id = "${element(azurerm_network_interface.nic.*.id, count.index)}"
ip_configuration_name = "ipconfig${count.index}"
# How can I pass in nat_rule_ids from module1?
# I dont think this will work.
nat_rule_id = "${element(var.nat_rule_ids, count.index)}"
count = "${var.availability_set_id != "" ? var.number_of_instances : 0}"
}
...
Questions:
1. How to pass the array of ids to module 2 as variables, so that module 2 can resolve and get the id, as the example code below.
2. Based on the structure that I have got, do you think is a good practice to manage all the variables ? is there any other better practice to manage them? since if i need to add 1 new variable in module 1, I need to update the variable across module2 and even all the template that call it.