Somethingwhatever
Somethingwhatever

Reputation: 1348

How to Use for loop with data in terraform?

I am trying to get the cluster_identifier and aws_db_snapshot for certain databases using a data file. My data.tf file looks like this :-

data "aws_rds_cluster" "cluster" {
  cluster_identifier = var.rds_sources
}

data "aws_db_snapshot" "db" {
  db_instance_identifier = var.rds_sources
  most_recent            = true
}

where rds_sources is a list(string). But when i do terraform plan i keep running into :-

Error: Incorrect attribute value type
│ 
│   on ../data.tf line 2, in data "aws_rds_cluster" "cluster":
│    2:   cluster_identifier = var.rds_sources
│     ├────────────────
│     │ var.rds_sources is a list of string, known only after apply
│ 
│ Inappropriate value for attribute "cluster_identifier": string required.
╵
╷
│ Error: Incorrect attribute value type
│ 
│   on ../data.tf line 6, in data "aws_db_snapshot" "db":
│    6:   db_instance_identifier = var.rds_sources
│     ├────────────────
│     │ var.rds_sources is a list of string, known only after apply
│ 
│ Inappropriate value for attribute "db_instance_identifier": string
│ required.

My question is how can i use for loop to get the necessary information? Thank you.

Upvotes: 0

Views: 1256

Answers (1)

Mark B
Mark B

Reputation: 200476

You said "for loop" so I assume you are wanting to use for_each although you could also use count here.

data "aws_rds_cluster" "cluster" {
  for_each = toset(var.rds_sources)

  cluster_identifier = each.key
}

data "aws_db_snapshot" "db" {
  for_each = toset(var.rds_sources)

  db_instance_identifier = each.key
  most_recent            = true
}

Note that you may need to be using aws_db_cluster_snapshot instead of aws_db_snapshot depending on your database engine.

Upvotes: 1

Related Questions