在使用Terraform的AWS中,仅当LB不存在时才必须创建负载平衡器资源。为此,我可以定义一个变量,例如“ lb_exists = true”,并基于此“ true”值,必须创建资源,否则,terraform应该跳过LB的创建。
为实现这一点,我计划安装depends_on。如果“ lb_exists = false”,则depends_on应该为空列表或设置为无资源名称。
locals {
lb_exists = "true"
}
resource "aws_lb" "test" {
name = var.alb_name
internal = false
load_balancer_type = "application"
#...
}
data "aws_lb" "test" {
lb_exists = "${local.lb_exists}"
depends_on = ["aws_lb.test"]
}
实现此目标的正确方法是什么?如何实现?有没有解决方法?我不想在AWS中存在的情况下重新创建LB。请提出建议。
[编辑] 复制完整的代码
provider "aws" {
region = var.aws_region
}
resource "aws_lb" "test" {
count = local.lb_exists == "true" ? 1 : 0
name = var.alb_name
internal = false
load_balancer_type = "application"
security_groups = var.alb_security_groups
subnets = var.alb_subnets
enable_deletion_protection = true
access_logs {
#bucket = aws_s3_bucket.lb_logs.bucket
bucket = "aws-lab-demo"
prefix = "test-lb-logs"
enabled = false
}
tags = {
Environment = var.env
Name = var.vpc_id
}
}
data "aws_lb" "test" {
# count = local.lb_exists == "true" ? 1 : 0
arn = "${aws_lb.test.arn}"
name = "${aws_lb.test.name}"
}
resource "aws_lb_target_group" "test" {
name = var.alb_name
port = 8080
protocol = "HTTP"
vpc_id = var.vpc_id
stickiness {
type = "lb_cookie"
cookie_duration = 1800
enabled = false
}
health_check {
healthy_threshold = 3
unhealthy_threshold = 10
timeout = 5
interval = 10
path = "/"
port = "8081"
}
}
data "aws_lb_target_group" "test" {
arn = "${aws_lb_target_group.test.arn}"
name = "${aws_lb_target_group.test.name}"
}
resource "aws_lb_listener" "front_end" {
load_balancer_arn = data.aws_lb.test.arn
port = "80"
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = data.aws_lb_target_group.test.arn
}
}
答案 0 :(得分:3)
有两种方法可以实现它:
terraform
应该创建多少个资源或数据源实例。对于您的情况,这可能是推荐的方法。resource "aws_lb" "test" {
count = local.lb_exists == "true" ? 1 : 0
...
}
如果您使用count
,则terraform
会创建资源列表,您应该像这样访问它们:aws_lb.test[0]
set
提供map
或for_each
。当您需要控制所创建的资源类型时,此方法很有用。例如,如果您有类似这样的内容:locals {
load_balancers = ["app1", "app2"]
}
resource "aws_lb" "test" {
# you can also make it conditional and provide an empty map
for_each = { for item in local.load_balanecers: item => item }
...
}
在这种情况下,terraform
创建一个资源映射,可以通过提供给for_each
的密钥来访问资源:aws_lb.test["app1"]