My answer for complex aws filters with terraform

Hello again friend. It’s the heat of the summer and I’ve been on a rather long engagement helping a client automate the build of EKS servers. One item I was keen to automate was the target subnet where the cluster gets installed and where to place the node group(s). So I turned to the aws_subnets data source object, which returns the all subnets in the vpc. It is up to us the humble devops to create a filter to return only the objects desired. The environment we were working in had two dev subnets that were non-standard named and thus throws off any simple filters. The solution for me was to use conditional filters. The code sets the filter value based on the “environment” variable. Each filter’s default response of is “*”, which means don’t filter. With the handy yet long-winded code it can return just the subnets needed.


Happy building,

D

data "aws_subnets" "cluster_subnets" {
  filter {
  name = "tag:Name"
  values =  (((var.tags["environment"] == "qa") || (var.tags["environment"] == "prod") || (var.tags["environment"] == "pre-prod"))  ? ["*${var.region}-app-1","*${var.region}-app-2","*${var.region}-app-3"]:["*"])
  }
  filter {
    name = "tag:Name"
    values = ((((var.tags["environment"] == "dev" && (var.account_id != "0123456789")) || var.tags["environment"] == "test"))  ? ["*${var.region}-app-1","*${var.region}-app-2"]:["*"])
  }
  filter {
    name = "tag:Name"
    values = var.account_id == "0123456789" ? ["snowflake-us-east-1-subnet*"] : ["*"]
  }
}
My answer for complex aws filters with terraform

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top