如何在EC2实例中使用terraform选择性地配置root_block_device



我正在使用terraform创建AWS EC2实例。将使用提供的ami id创建实例。在terraform中,root_block_device块可用于配置根卷。
我想根据变量使此配置为可选的。因此,如果root_block_override变量为真,则使用提供的值;否则使用镜像中的根卷配置。

下面的地形抛出错误An argument named "count" is not expected here.

如何可选地配置根目录?

resource "aws_instance" "ec2" {
ami                    = var.ami_id
instance_type          = var.instance_type
iam_instance_profile   = aws_iam_instance_profile.ec2.name
key_name               = var.key_name
vpc_security_group_ids = var.security_group_ids
subnet_id              = var.subnet_id
user_data_base64       = base64encode(templatefile(var.user_data_file_path, var.user_data_variables))
root_block_device {
count                 = var.root_block_override ? 1 : 0
delete_on_termination = var.root_block_delete_on_termination
encrypted             = true
iops                  = var.root_block_volume_type == "gp2" ? null : var.root_block_iops
kms_key_id            = var.root_block_kms_key_id
throughput            = var.root_block_throughput
volume_size           = var.root_block_volume_size
volume_type           = var.root_block_volume_type
}
}

您可以使用for_each[1]元参数和dynamic[2]块的组合:

dynamic "root_block_device" {
for_each = var.root_block_override ? [1] : []
content {
delete_on_termination = var.root_block_delete_on_termination
encrypted             = true
iops                  = var.root_block_volume_type == "gp2" ? null : var.root_block_iops
kms_key_id            = var.root_block_kms_key_id
throughput            = var.root_block_throughput
volume_size           = var.root_block_volume_size
volume_type           = var.root_block_volume_type
}
}

[1] https://developer.hashicorp.com/terraform/language/meta-arguments/for_each

[2] https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks

最新更新