Is it possible to create S3 Bucket and store the statefile in the same s3 bucket backend?

I am planning to provision a S3 Bucket via terraform and store my statefile in the same Bucket.

I am curious to know if it’s posssible?

Thanks in advance.

Hi @yeshwanth18sa,

It is possible to do this but it requires a special bootstrapping procedure, so I’d suggest using it only with a very small configuration that only manages the infrastructure for state storage and locking.

The bootstrap procedure is:

  • Temporarily remove (or comment out) the backend block before your first apply, so that Terraform will default to using local state storage.
  • Run terraform init to configure the local backend.
  • Run terraform apply to create your S3 bucket and any other infrastructure the backend will depend on, such as DynamoDB or IAM objects.
  • Now add your backend block back into the configuration, referring to the objects you just created.
  • Run terraform init again, and Terraform should offer to migrate the state to the new backend configuration. If you agree, it will copy the local state file into S3.
  • Run terraform plan to verify that it successfully produces an empty plan.

As long as you never need to recreate the infrastructure for the backends, you can now use this configuration as normal. However, if you do one day need to recreate this infrastructure you’ll need to perform the opposite procedure of migrating back to local again first, making the changes, and migrating back to remote again. It’s for that reason that I suggest keeping this configuration as small as possible, so that it’s rare that you’ll need to work with it in ways that might require taking these unusual steps.