If my google-fu has failed and this has been asked, please ignore.
I need to create a list of availability zones in my region and spin up private and public subnets in each. I’ve found lots of info on data, templates, and files external to the tf plan itself but these do not answer my use case.
I have attempted using the data.aws_availability_zones.available
, along with count
to get a list of availability zones my subnets can actually be spun up in. As others have found, the list includes availability zones that subnets are not allowed to spin up in.
So, I wanted to try and pass in a provisioner:local_exec
command and have the results flow into a variable list, which works at command line:
"
provisioner “local-exec” {
command = <<EOF
“aws --profile “dev” ec2 --region us-west-1 describe-availability-zones |
grep “ZoneName” |
awk ‘{ print $2 }’ >>>var.AZs”
EOF
}
However, I am still getting the same error:
“Error: error creating subnet: InvalidParameterValue: Value (var.AZs.[count.index]) for parameter availabilityZone is invalid. Subnets can currently only be created in the following availability zones: us-west-1a, us-west-1c. status code: 400, request id:”
This is the script:
provider “aws” {
profile = var.profile
region = var.region
}
resource “aws_vpc” “vpcTest” {
cidr_block = “10.0.0.0/16”
enable_dns_hostnames = true
tags = {
Name = “vpcTest”
}
}
variable “AZs” {
type = list(string)
default = [ “us-west-1a”, “us-west-1c” ]
}
resource “aws_subnet” “TestPublic_subnet” {
provisioner “local-exec” {
command = <<EOF
“aws --profile “myprof” ec2 --region us-west-1 describe-availability-zones |
grep “ZoneName” |
awk '{ print $2,”," }’ >>>var.AZs"
EOF
}
count = 2
vpc_id = “aws_vpc.vpcTest.id”
cidr_block = “10.0.${10+count.index}.0/24”
availability_zone = “var.AZs.[count.index]”
map_public_ip_on_launch = true
tags = {
Name = “PublicSubnet”
}
}
resource “aws_subnet” “TestPrivate_subnet” {
provisioner “local-exec” {
command = <<EOF
“aws --profile “myprof” ec2 --region us-west-1 describe-availability-zones |
grep “ZoneName” |
awk ‘{ print $2 }’ >>>var.AZs”
EOF
}
count = 2
vpc_id = “aws_vpc.vpcTest.id”
cidr_block = “10.0.${20+count.index}.0/24”
availability_zone = “var.AZs.[count.index]”
map_public_ip_on_launch = false
tags = {
Name = “PrivateSubnet”
}
}
resource “aws_security_group” “webtraffic” {
name = “TestAllow-HTTPS”
vpc_id = aws_vpc.vpcTest.id
ingress {
from_port = 443
to_port = 443
protocol = “TCP”
cidr_blocks = [ aws_vpc.vpcTest.cidr_block ]
}
}