我有一个定义 ECS 集群的 ecs_cluster
模块。我希望模块可以重复使用,这样我就可以创建具有不同配置的各种集群。因此,我希望能够有选择地指定是否在 ECS 主机的启动配置中创建和附加 EBS 卷。
我最初尝试在启动配置中的 ebs_block_device
中使用 count
,例如
variable "ebs_volume_device_name" { type = "string", default = "" }
variable "ebs_volume_type" { type = "string", default = "" }
variable "ebs_volume_size" { type = "string", default = "" }
resource "aws_launch_configuration" "launch_configuration" {
name_prefix = "foo"
image_id = "bar"
# Irrelevant stuff removed for brevity...
ebs_block_device {
count = "${length(var.ebs_volume_device_name) > 0 ? 1 : 0}"
device_name = "${var.ebs_volume_device_name }"
volume_type = "${var.ebs_volume_type}"
volume_size = "${var.ebs_volume_size}"
}
}
但是这会导致以下错误:
module.ecs_cluster.aws_launch_configuration.launch_configuration: ebs_block_device.0: invalid or unknown key: count
然后我尝试指定 launch_configuration 资源两次,一次使用 ebs block 设备,一次不使用,例如
variable "ebs_volume_device_name" { type = "string", default = "" }
variable "ebs_volume_type" { type = "string", default = "" }
variable "ebs_volume_size" { type = "string", default = "" }
resource "aws_launch_configuration" "launch_configuration" {
count = "${length(var.ebs_volume_device_name) == 0 ? 1 : 0}"
name_prefix = "foo"
image_id = "bar"
# Irrelevant stuff removed for brevity...
# No specification of ebs_block_device
}
resource "aws_launch_configuration" "launch_configuration" {
count = "${length(var.ebs_volume_device_name) > 0 ? 1 : 0}"
name_prefix = "foo"
image_id = "bar"
# Irrelevant stuff removed for brevity...
ebs_block_device {
device_name = "${var.ebs_volume_device_name }"
volume_type = "${var.ebs_volume_type}"
volume_size = "${var.ebs_volume_size}"
}
}
但是 Terraform 然后会提示,因为资源被定义了两次。
我无法更改任何一个资源的 ID,因为我有一个自动缩放组,它取决于启动配置的名称,例如
resource "aws_autoscaling_group" "autoscaling_group" {
name = "foo"
launch_configuration = "${aws_launch_configuration.launch_configuration.name}"
}
我想我可以有条件地定义 2 个自动缩放组并将一个映射到每个启动配置,但这感觉真的很困惑。此外,这些资源本身具有依赖资源,例如 cloudwatch 指标警报等。使用 2 个单独的条件将所有这些代码重复两次感觉非常不干。我在这里错过了一个技巧吗?
感谢任何相关的 Terraform 智慧!
最佳答案
不幸的是,计数元属性仅适用于资源级别。在资源(例如您的 ebs_block_device 或例如日志记录等)中有一个条件 block 是 github 中的 terraform issues 中经常提到的一个问题,据我所知还没有解决方案。
在你的情况下,一个“技巧”可能是让你的 autoscaling_group.launch_configuration 属性也有一个三元运算符,即
resource "aws_autoscaling_group" "autoscaling_group" {
name = "foo"
launch_configuration = "${length(var.ebs_volume_device_name) == 0 ? aws_launch_configuration.launch_configuration.name : aws_launch_configuration.launch_configuration2.name}"
}
或者更好的是将该逻辑提取到具有输出名称的 launch_configuration 模块中,然后上面的代码看起来像
resource "aws_autoscaling_group" "autoscaling_group" {
name = "foo"
launch_configuration = "${module.launch_config.name}"
}
并不是说它不丑,但这是 terraform 的条件语句。
关于Terraform:如何有条件地将 EBS 卷分配给 ECS 集群,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45442805/