Search code examples
amazon-web-servicesterraform

How to create multiple resources in one main.tf file with Terraform module


I have created a simple Terraform module to create S3 buckets. It works fine when I want to create only one bucket, but what if I want to create multiple buckets? Surely, I don't need a main.tf file for every bucket I want to create? I realise this is a noob question, but would be grateful for any help.

So instead of doing this (which produces an error anyway), what's the correct approach if all I want to change is the bucket name and tag in the same main.tf file? Can I create a list of bucket names and iterate over them?

module "s3_buckets" {
  source       = "../modules/s3_buckets"
  bucket_name = "my-tf-bucket-1"
  tag          = "tf"
}

module "s3_buckets" {
  source       = "../modules/s3_buckets"
  bucket_name = "my-tf-bucket-2"
  tag          = "tf"
}

Solution

  • You can use the for-each meta-argument. This could be something like:

    module "s3_buckets" {
      for_each = toset(["my-tf-bucket-1", "my-tf-bucket-2"])
      source       = "../modules/s3_buckets"
      bucket_name  = each.key
      tag          = "tf"
    }