如何使用Terraform从VPC获取子网列表

时间:2019-10-16 02:13:46

标签: terraform terraform-provider-aws aws-batch

我尝试使用以下代码获取所有子网ID以添加带有Terraform的AWS批处理:

data "aws_subnet_ids" "test_subnet_ids" {
  vpc_id = "default"
}
data "aws_subnet" "test_subnet" {
  count = "${length(data.aws_subnet_ids.test_subnet_ids.ids)}"
  id    = "${tolist(data.aws_subnet_ids.test_subnet_ids.ids)[count.index]}"
}

output "subnet_cidr_blocks" {
  value = ["${data.aws_subnet.test_subnet.*.id}"]
}

幸运的是,经过我的测试,它工作正常。但是当我尝试与批处理terraform集成时,

resource "aws_batch_compute_environment" "test-qr-processor" {
  compute_environment_name = "test-qr-processor-test"
  compute_resources {
    instance_role = "${aws_iam_instance_profile.test-ec2-role.arn}"
    instance_type = [
      "optimal"
    ]
    max_vcpus = 256
    min_vcpus = 0
    security_group_ids = [
      "${aws_security_group.test-processor-batch.id}"
    ]
    subnets = ["${data.aws_subnet.test_subnet.*.id}"]
    type = "EC2"
  }
  service_role = "${aws_iam_role.test-batch-service-role.arn}"
  type = "MANAGED"
  depends_on = [ "aws_iam_role_policy_attachment.test-batch-service-role" ]
}

我遇到了以下错误消息,

  

错误:属性值类型错误

     

在terraform.tf第142行中,在资源中   “ aws_batch_compute_environment”“测试处理器”:142:子网=   [“ $ {data.aws_subnet.test_subnet。*。id}”]

     

属性“子网”的值不合适:元素0:字符串   必填。

请让我知道为什么,谢谢。

1 个答案:

答案 0 :(得分:1)

"${data.aws_subnet.test_subnet.*.id}"已经是string array类型。

您应该输入不带[ ]

的值

编写如下代码:

subnets = "${data.aws_subnet.test_subnet.*.id}"
  

请参阅:

     

这里有A document关于Resource: aws_batch_compute_environment