view Terraform output from module using for_each and toset

i have a simple terraform script which makes use of a module, the script creates multiple s3 buckets:

main.tf:

variable "bucket_name"{
    type = list
    description = "name of bucket"
}

module "s3" {
    source = "../modules/s3"
    for_each = toset(var.bucket_name)
    bucket_name = "${each.key}"
}

outputs.tf

output "arn" {
  description = "ARN of the bucket"
  value       = module.s3.arn
}

names.tfvars:

bucket_name = ["bucket-a", "bucket-b"]

modules/s3/main.tf:

resource aws_s3_bucket "mybucket" {
    bucket = var.bucket_name
    }

modules/s3/variables.tf

variable "bucket_name" {
  type    = string
  default = ""
}

modules/s3/outputs.tf

output "arn" {
  description = "Name of the bucket"
  value       = aws_s3_bucket.mybucket.arn
}

The issue i have is when i run a plan i get the following error:

│     │ module.s3 is object with 2 attributes
│
│ This object does not have an attribute named "arn".

i’m trying to access the arn of the generated buckets but unsure of where i have gone wrong

>Solution :

Since you are using for_each, you have to access individual instances of your module, such as module.s3["bucket-a"].arn.

If you want to get the list of all ARNs of your buckets generated by the module, then it should be:

output "arn" {
  description = "ARN of the bucket"
  value       = values(module.s3)[*].arn
}

Leave a Reply