Search code examples
amazon-web-servicesterraformterraform-provider-awsterraform-template-file

How to avoid cycle error when setting an S3 bucket policy with a template that depends on the bucket name?


I have a terraform file which fails when I run terraform plan and I get the error:

Error: Cycle: module.hosting.data.template_file.bucket_policy, module.hosting.aws_s3_bucket.website

It makes sense since the bucket refers to the policy and vice versa:

data "template_file" "bucket_policy" {
  template = file("${path.module}/policy.json")
  vars = {
    bucket = aws_s3_bucket.website.arn
  }
}

resource "aws_s3_bucket" "website" {
  bucket = "xxx-website"

  website {
    index_document = "index.html"
  }

  policy = data.template_file.bucket_policy.rendered
}

How can I avoid this bidirectional reference?


Solution

  • You could build the ARN of the bucket yourself:

    locals {
      bucket_name = "example"
      bucket_arn  = "arn:aws:s3:::${local.bucket_name}"
    }
    
    data "template_file" "bucket_policy" {
      template = file("${path.module}/policy.json")
      vars = {
        bucket = local.bucket_arn
      }
    }
    
    resource "aws_s3_bucket" "website" {
      bucket = local.bucket_name
    
      website {
        index_document = "index.html"
      }
    
      policy = data.template_file.bucket_policy.rendered
    }