Search code examples
google-cloud-platformterraformterraform-provider-gcp

Issue with terraform GCS output


I have written a terraform module which can create multiple cloud storage buckets.Its working fine but it has issue in creating outputs.

main.tf

resource "google_storage_bucket" "buckets" {
    name     = var.name_bucket 
    project = var.project_id

output.tf

output "bucket_name" {
  value = google_storage_bucket.buckets.name
}
output "self_link" {
  value = google_storage_bucket.buckets.self_link
}
output "url" {
  value = google_storage_bucket.buckets.url  
}
output "lifecycle_rule" {
  value = local.lifecycle_rules
}

iam.tf

resource "google_storage_bucket_iam_member" "object_viewer" {
  for_each = toset(var.object_viewers)
  member = each.key
  bucket = google_storage_bucket.buckets.name
  role  = "roles/storage.objectViewer"
}

I am able to provide the users objectviewer role.

Then i am calling the above module using below

main.tf

module "s3bucks-cloud-storage" {
  for_each = local.s3bucks-buckets
  .
  .
  .
}

output.tf

output "names" {
  description = "Bucket names."
  value       = module.s3bucks-cloud-storage.bucket_name
}

Error

│ Error: Unsupported attribute │ │ on outputs.tf line 4, in output "names": │ 4: value = module.s3bucks-cloud-storage.bucket_name │ ├──────────────── │ │ module.s3bucks-cloud-storage is object with 3 attributes │ │ This object does not have an attribute named "bucket_name".

I think i have used the correct syntax to generate output but not sure why i am getting this error.I want to output all the values which i have used in main module


Solution

  • Since the module is called using also the for_each meta-argument, you need to reference the module by the key in order to get a value from it. So, to get all the bucket names, you should do the following:

    output "names" {
      description = "Bucket names."
      value       = values(module.s3bucks-cloud-storage)[*].bucket_name
    }
    

    The values built-in function will fetch the bucket_name values for all the keys (denoted by [*]).