How to get Subnet list from VPC with terraform
Asked Answered
C

1

10

I've tried to get all subnet ids to add aws batch with terraform with following code:

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}"]
}

Fortunately, it was working fine when I've tested like that. But when I tried to integrate with batch terraform like:

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" ]
}

I've encountered following error message,

Error: Incorrect attribute value type

on terraform.tf line 142, in resource "aws_batch_compute_environment" "test-processor": 142: subnets = ["${data.aws_subnet.test_subnet.*.id}"]

Inappropriate value for attribute "subnets": element 0: string required.

Please let me know why, thanks.

Cornetcy answered 16/10, 2019 at 2:13 Comment(0)
S
15

"${data.aws_subnet.test_subnet.*.id}" is already string array type.

you should input value without [ ]

write code like :

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

See :

Here's A document about Resource: aws_batch_compute_environment

Schiller answered 16/10, 2019 at 4:34 Comment(4)
How can I filter out public subnets and get only the private ones?Hutcheson
@Hutcheson Hi, you can find it in this repository's vpc.tf fileSchiller
@Schiller that file already starts with private and public subnets separated in the locals variable at the top. It doesn't answer Shell_Leko 's questionLeopoldeen
@Shell_Leko, This might help you: https://mcmap.net/q/571913/-aws-terraform-filter-specific-subnets-by-matching-substring-in-tag-nameBlasien

© 2022 - 2024 — McMap. All rights reserved.