I have pre-built subnets in each of my three AWS Availability Zones. I need to build an EC2 instance per AZ but they need to use specific subnets that already exist.
How do I go about writing this in Terraform?
I've got this so far:.
# Configure the AWS Provider
provider "aws" {
region = "eu-west-1"
}
# Specify 3 availability zones from the region
variable "availability_zones" {
default = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
}
data "aws_subnet_ids" "private" {
vpc_id = "${data.aws_vpc.selected.id}"
tags {
Name = "private-elb-1a*"
}
}
#create ec2 instance
resource "aws_instance" "linux-terraform-test-inst" {
ami = "ami-0b77cxxxxxxx" #Ubuntu x86_64
instance_type = "t3.micro"
subnet_id = "subnet-xxxxxx"
security_groups = [aws_security_group.sgn-linux-terraform-test.id]
tags = {
Name = "linux-terraform-test-inst"
}
}
#create security group with allowed port and IP ranges
resource "aws_security_group" "sgn-linux-terraform-test" {
name = "sgn-linux-terraform-test"
description = "sgn-linux-terraform-test"
vpc_id = "vpc-052xxxxxxxxxxx"
ingress {
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["172.16.0.0/12", "10.0.0.0/8"]
}
ingress {
description = "HTTPS"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "HTTPS Test port"
from_port = 7443
to_port = 7443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "sgn-linux-terraform-test"
}
}
Hard coding works, but would like for it to be a bit more dynamic. Each subnet in each AZ has a similar name pattern like 'private-elb-*' that could possibly be used.
AZ "eu-west-1a" has a subnet named "private-elb-1a", "eu-west-1b" has a subnet named "private-elb-1b" and "eu-west-1c" has a subnet named "private-elb-1c".
I have thought of using something like this I picked up on another thread. Just not sure how to construct it to use the specific name of an existing subnet.
{ for s in data.aws_subnet.vpc_live : s.availability_zone => s.id... }