Terraform tip #01
You are using Terraform to set up your infrastructure.
Depending on the resource you need to have a list of your Public or Private subnets. So when you are starting, and just need to get that thing done, you pass to the module a list of the subnets created previously and maybe the id of your VPC.
Now that seemed not the best way to do since I try to keep my modules dry and independent.
So, how do you get that list of subnets id's automatically? Here is a tip for you:
When you create your subnets add this tag:
tags = {
Tier = "Private"
}
or
tags = {
Tier = "Public"
}
Then, when you need to get a private or public subnet id's, use the Tier tag as filter:
data "aws_subnet_ids" "default" {
vpc_id = var.vpc_id
tags = {
Tier = "Private"
}
}
And to get the subnets instances:
data "aws_subnet" "default" {
count = length(data.aws_subnet_ids.default.ids)
id = tolist(data.aws_subnet_ids.default.ids)[count.index]
}
That is it! You are good to manage those subnets, without the need to pass the list from previous modules and maybe get the wrong subnets.
You can also filter the VPC id from the name of it, but and get that on data "aws_vpc" using terraform filter like this:
data "aws_vpc" "selected" {
filter {
name = "tag:Name"
values = [var.vpc_name]
}
}
So you don't need to pass as a variable the VPC id, but for that, you need to have a pattern of the naming of the VPC and other resources, and that is my case, but still, I am lazy(for now).
That's all folks.