How Terraform uses conditional logic to dynamically create resources
background
As we (probably) know, Terraform does not support if statements.
Fortunately, we can count
achieve the same result by using a specific parameter named .
We can think of it this way: the count can be set to 1, that is, a copy of the resource is obtained.
However, setting the same count parameter to 0 will not create any resources.
So, as mentioned, you don't need if/else statements at all, terrform uses conditional expressions in the following format:
<CONDITION> ? <TRUE_VAL> <FALSE_VAL>
All Terraform does is CONDITION
compute boolean logic in , based on which, if the value is true, it will return TRUE_VAL
; otherwise, if the result is false, it will return FALSE_VAL
.
the case
For example, we will be migrating our existing AWS infrastructure (previously based on Ansible & Boto3 deployments) in terrraform.
This example is about ELB creation, which contains a target group and a listener .
Taken from a migration project I'm currently working on, it will actually show what I just explained:
resource "aws_lb_target_group" "tg" {
count = var.target_group_addition ? 1 : 0
name = "tg-${var.name}"
port = var.tg_port
protocol = var.tg_protocol
vpc_id = var.vpc_id
deregistration_delay = var.tg_deregistration_delay
health_check {
interval = var.tg_healthcheck_interval
path = var.tg_healthcheck_path
port = "traffic-port"
protocol = var.tg_protocol
timeout = 5
healthy_threshold = 2
unhealthy_threshold = 2
matcher = var.tg_healthcheck_success_code
}
}
As you can see, the resource is only created if the booleanvar.target_group_add
assigned to is set to aws_lb_target_group .true(1)
in conclusion
count
This is a very simple way of handling if statements in Terraform, and shows how to use properties in Terraform to do dynamic resource configuration when needed .
REF:
https://medium.com/swlh/terraform-how-to-use-conditionals-for-dynamic-resources-creation-6a191e041857
Follow the official account: "Cloud Native SRE"