首页 > 解决方案 > 在 terraform 中创建多个负载均衡器、目标组和侦听器

问题描述

有没有办法用新资源附加到现有状态文件,或者用所有其他相关资源创建多个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
}

标签: amazon-web-servicespowershellterraform

解决方案


首先,让我解释一下为什么您的 ALB 会被覆盖:

Terraform 是一种声明性的,即它使环境与文件中的外观完全相同。因此,如果您使用名称ALB1和一些配置创建 ALB,运行 Terraform,然后将文件中的名称更改为ALB2,调用 Terraform apply,Terraform 将删除第一个(因为您需要新资源来重命名 ALB)并创建一个新的一。

使用Terraform Modules可以轻松实现您想要的。您可以执行以下操作:

  1. 将所有信息以及变量(您可能需要更多变量)导出到模块中。模块只是您拥有的文件夹,例如Main.tfvars.tfoutput.tf
  2. 然后从另一个 Terraform 文件中,您将使用所需的每个负载均衡器的适当值多次调用您的模块。

检查以获取有关模块的更多信息。

PS如果您发现自己对此感到困惑,请发表评论,我们会解决它。


推荐阅读