Belal Khan
Belal Khan

Reputation: 1

Terraform Reference Created S3 Bucket for Remote Backend

I'm trying to setup a remote Terraform backend to S3. I was able to create the bucket, but I used bucket_prefix instead of bucket to define my bucket name. I did this to ensure code re-usability within my org.

My issue is that I've been having trouble referencing the new bucket in my Terraform back end config. I know that I can hard code the name of the bucket that I created, but I would like to reference the bucket similar to other resources in Terraform.

Would this be possible?

I've included my code below:

#configure terraform to use s3 as the backend
terraform {
   backend "s3" {
      bucket         = "aws_s3_bucket.my-bucket.id"
      key            = "terraform/terraform.tfstate"
      region         = "ca-central-1"    
   }
}

AWS S3 Resource definition

resource "aws_s3_bucket" "my-bucket" {
    bucket_prefix = var.bucket_prefix

    acl = var.acl

    lifecycle {
        prevent_destroy = true
    }

    versioning {
        enabled = var.versioning
    }

    server_side_encryption_configuration {
        rule {
            apply_server_side_encryption_by_default {
               sse_algorithm = var.sse_algorithm
            }
        }
    }
}

Upvotes: 0

Views: 2085

Answers (1)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16805

Terraform needs a valid backend configuration when the initialization steps happens (terraform init), meaning that you have to have an existing bucket before being able to provision any resources (before the first terraform apply).

If you do a terraform init with a bucket name which does not exist, you get this error:

The referenced S3 bucket must have been previously created. If the S3 bucket
│ was created within the last minute, please wait for a minute or two and try
│ again.

This is self explanatory. It is not really possible to have the S3 bucket used for backend and also defined as a Terraform resource. While certainly you can use terraform import to import an existing bucket into the state, I would NOT recommend importing the backend bucket.

Upvotes: 2

Related Questions