我正在尝试创建一个负载均衡器,并将目标组附加到ALB,并将侦听器和实例附加到目标组。
我已经将它用于单个负载均衡器,但是我无法使其在多个ALB上运行而不必重复代码。
我也尝试在命令行中传递输入变量,并在powershell中添加脚本,但是每次创建资源时,状态文件都会用下一个资源名称覆盖。
是否可以使用新资源将现有状态文件追加到现有状态文件中,或者可以使用其他所有相关资源创建多个alb而不进行复制?
下面是代码:
variable` "name" {}
variable "environment" {
default = "Beta"
}
variable "security_group_id" {
default = ["sg-xxxxxx"]
}
variable "subnet_ids" {
type = "list"
default = ["subnet-xxxxxx","subnet-xxxxxxx","subnet-xxxxxxxxxxx"]
}
variable "instance_ids" {
type = "list"
default = ["xxxxxxx","xxxxxxx"]
}
variable "vpc_id" {
default = "vpc-xxxxxxxxxxxx"
}
variable "ssl_certificate_arn" {
default = "vpc-xxxxxxxxxxx"
}
provider "aws" {
region = "us-west-2"
access_key = "xxxxxxxxxx"
secret_key = "xxxxxxxxxx"
}
resource "aws_alb" "alb" {
count = "1"
name = "${var.name}-${var.environment}"
internal = false
security_groups = ["${var.security_group_id}"]
subnets = ["${var.subnet_ids}"]
tags {
Environment = "${var.environment}"
}
}
resource "aws_alb_target_group" "alb_targets" {
count = "1"
name = "${var.name}-${var.environment}"
port = "80"
protocol = "HTTP"
vpc_id = "${var.vpc_id}"
health_check {
healthy_threshold = 2
interval = 15
path = "/api/health"
timeout = 10
unhealthy_threshold = 2
}
tags {
Environment = "${var.environment}"
}
}
resource "aws_alb_listener" "alb_listener" {
count = "1"
load_balancer_arn = "${aws_alb.alb.arn}"
port = "80"
protocol = "HTTP"
#ssl_policy = "ELBSecurityPolicy-2015-05"
#certificate_arn = "${var.ssl_certificate_arn}"
default_action {
target_group_arn = "${element(aws_alb_target_group.alb_targets.*.arn, 0)}"
type = "forward"
}
}
resource "aws_lb_target_group_attachment" "test" {
target_group_arn = "${aws_alb_target_group.alb_targets.arn}"
target_id = "${element(var.instance_ids,count.index)}"
port = 80
}
答案 0 :(得分:1)
首先,让我解释一下为什么您的ALB会被覆盖:
Terraform是声明性,即,它可以使Environment完全符合文件中的外观。因此,如果您使用名称 ALB1 创建ALB并进行一些配置,运行Terraform,然后将文件中的名称更改为 ALB2 ,则调用Terraform apply,Terraform将删除第一个(因为您需要使用新资源来重命名ALB)并创建一个新资源。
您可以使用 Terraform模块轻松实现所需的目标。您可以执行以下操作:
检查this以获得有关模块的更多信息。
P.S。如果您发现自己对此一无所知,请发表评论,我们将予以解决。