Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-else condition in terraform data source

My question is very simple but unable to find any example or solution on the entire internet. I want to use the if-else condition in the data source of terraform and based on the value it should search the result. We have 2 different VPCs in our AWS account: 1. Prod VPC, 2. RDS VPC

Filter should work based on boolean variable var.rds_vpc

Pseudocode:

data "aws_vpc" "vpc" {
  if var.rds_vpc == true:
    tags = {
      Name = "rds_vpc"
      Type = "database"
    }
  else:
    tags = {
      Cluster     = "live_vpc"
      Enviornment = "production"
    }

}

If both VPCs could have similar tags, I could simply pass the values via variables. But in the above case, the tags are also different.

I would highly appreciate it if someone can help.

like image 239
Alok Nath Avatar asked Sep 01 '25 04:09

Alok Nath


1 Answers

You can do it with count statement and ternary operator combination.

data "aws_vpc" "vpc" {
    tags = {
      Name = "rds_vpc"
      Type = "database"
    }
    count = var.rds_vpc == true ? 1 : 0
}
data "aws_vpc" "vpc" {
    tags = {
      Cluster     = "live_vpc"
      Enviornment = "production"
    }
    count = var.rds_vpc == true ? 0 : 1
}

you can pass tags to resource like this maybe.

variable tag_x {
    type = map(string)
}

variable tag_y {
    type = map(string)
}

tag_x = {
    Name = "rds_vpc"
    Type = "database"
}

tag_y = {
      Cluster     = "live_vpc"
      Enviornment = "production"
}

data "aws_vpc" "vpc" {
    tags = var.rds_vpc == true ? var.tag_x : var.tag_y
}
like image 94
m303945 Avatar answered Sep 02 '25 16:09

m303945