terraform
As you (probably) know, Terraform doesn’t support if statements.Luckily we can achieve the same result by using a specific parameter called count.
如您所知(可能),Terraform不支持if语句。幸运的是,我们可以通过使用称为count的特定参数来实现相同的结果。
You can think about it this way: you can set count to 1 on a specific resource and get one copy of that resource.
您可以这样考虑:可以将特定资源的count设置为1,并获得该资源的一个副本。
However, setting the same count parameter to 0 you won’t get any resource created.
但是,将相同的count参数设置为0将不会创建任何资源。
So, as already mentioned, you won’t need if/else statements at all, Terraform use conditional expressions with the following format:
因此,正如已经提到的,您根本不需要if / else语句,Terraform使用以下格式的条件表达式:
<CONDITION> ? <TRUE_VAL> <FALSE_VAL>
All that Terraform does is nothing but evaluating the boolean logic in CONDITION and, based on that, if the value is true it will return TRUE_VAL otherwise it’ll return FALSE_VAL if the result is false.
Terraform所做的全部工作只是在CONDITION中评估布尔逻辑,并且基于此,如果值为true ,则将返回TRUE_VAL,否则,如果结果为false ,则将返回FALSE_VAL。
Just to give you some contest, we’re migrating our existing AWS infrastructure (Ansible&Boto3 deployed) in Terraform.
只是为了给您一些竞赛,我们正在Terraform中迁移现有的AWS基础架构(已部署Ansible&Boto3)。
This particular example is referred to ELB creation with a target group and a listener. is taken from a migration project I’m currently working on and it will practically show what I’ve just explained:
此特定示例涉及具有目标组和侦听器的ELB创建。 摘自我目前正在从事的一个迁移项目,它实际上将显示我刚刚解释的内容:
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 aws_lb_target_group only will be created if the boolean value assigned to var.target_group_addition is set to true (1).
如您所见,仅当分配给var.target_group_addition的布尔值设置为true(1)时,才会创建资源aws_lb_target_group 。
This is a very simple way to handle if statements (kinda of) in Terraform and shows how using count
attribute in Terraform allows you to play with dynamic resource configuration when needed.
这是处理Terraform中的if语句(类型)的一种非常简单的方法,并显示了在Terraform中使用count
属性如何允许您在需要时使用动态资源配置。
terraform