amazon-web-services - 在 terraform 中创建多个负载均衡器、目标组和侦听器
问题描述
我正在尝试创建一个负载均衡器,其目标组连接到 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
}
解决方案
首先,让我解释一下为什么您的 ALB 会被覆盖:
Terraform 是一种声明性的,即它使环境与文件中的外观完全相同。因此,如果您使用名称ALB1和一些配置创建 ALB,运行 Terraform,然后将文件中的名称更改为ALB2,调用 Terraform apply,Terraform 将删除第一个(因为您需要新资源来重命名 ALB)并创建一个新的一。
使用Terraform Modules可以轻松实现您想要的。您可以执行以下操作:
- 将所有信息以及变量(您可能需要更多变量)导出到模块中。模块只是您拥有的文件夹,例如Main.tf、vars.tf、output.tf
- 然后从另一个 Terraform 文件中,您将使用所需的每个负载均衡器的适当值多次调用您的模块。
检查此以获取有关模块的更多信息。
PS如果您发现自己对此感到困惑,请发表评论,我们会解决它。
推荐阅读
- python - DatasetV1Adapter 返回意外的数据类型
- regex - 正则表达式在第一行和第二行添加符号
- ios - Swift:如何将项目分组或俱乐部下载到一个单元格 tableView
- python - 如何像列表一样在外部使用 csv_reader 对象?
- internet-explorer - 如何在 IE 中重新加载页面时销毁 websocket
- angular - ng add@angular-material // 你尝试添加的包不支持原理图
- android - Expokit - 从 SDK 32 升级到 SDK 36 后,启动屏幕未在 Android 上显示
- odata - 如何获得这些查询的正确结果?
- variables - 单击运行管道时未显示 Azure YAML 管道变量
- javascript - 删除数组元素失败