Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading