Terraform use data resource to get Cluster Snapshot?

Viewed 35

I have a global Aurora RDS cluster that takes automated snapshot everyday. My DB instance looks like this :-

new-test ( Global Database )
   
new-test-db ( Primary Cluster )

new-test-db-0 ( Writer Instance )

I have enabled automated snapshots for the db. What i am trying to achieve is to get the ARN for my snapshot using data resource. My ARN is something like this :-

arn:aws:rds:us-west-2:123456789101:cluster-snapshot:rds:new-test-db-2022-08-23-08-06

This is what my data resource looks like :-

data "aws_db_cluster_snapshot" "db" {
  for_each               = toset(var.rds_sources)
  db_cluster_identifier  = each.key
  most_recent            = true
}

where var.rds_sources is a list of strings. But when i try to access the arn using :-

data.aws_db_cluster_snapshot.db[*].db_cluster_snapshot_arn

I keep running into

 Error: Unsupported attribute
│ 
│   on ../main.tf line 73, in resource "aws_iam_policy" "source_application":
│   73:     cluster_data_sources  = jsonencode(data.aws_db_cluster_snapshot.db[*].db_cluster_snapshot_arn)
│ 
│ This object does not have an attribute named "db_cluster_snapshot_arn".

Which is weird since the attribute is laid out in the official docs. Thank you for the help.

This is my provider file :-

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.75"
    }
    archive = "~> 2.2.0"
  }
  required_version = "~> 1.2.6"
}
1 Answers

Since the data source is using for_each, the result will be a map of key value pairs. In terraform, there is a built-in function values [1] which can be used to fetch the values of a map. The return value is a list, so in order to get all the values for all the keys the splat operator is used [2]. Then, since the data source is returning multiple attributes and only one is required (namely db_cluster_snapshot_arn), the final expression needed is as follows:

jsonencode(values(data.aws_db_cluster_snapshot.db)[*].db_cluster_snapshot_arn)

[1] https://www.terraform.io/language/functions/values

[2] https://www.terraform.io/language/expressions/splat

Related