State is a necessary requirement for Terraform to function. It is often asked if it is possible for Terraform to work without state, or for Terraform to not use state and just inspect cloud resources on every run. This page will help explain why Terraform state is required.
It is possible to create the backend bucket manually as most documentation suggests, this repo is provided as an alternative to make sure the bucket is created according to our Cloud Code of Conduct policy (encryption, versioning, not public).
If state file is required for this specific configuration make sure you save it manually in a secure location, or use a previously created backend.
This example uses AES-256 server-side encryption, it is also possible to use aws:kms. More info is available here.
- Update Variables in variables.tf file
- variable "owner"
- variable "bucket_name"
- variable "product"
- make sure aws cli is configured for correct aws account.
- run
terraform init
- run
terraform plan
- run
terraform apply
Once the backend is created in your target account you can add the following snippet into your main.tf file. The backend config should be placed in the Terraform block, the terraform block can only contain constants so all values need to be manually entered.
provider "aws" {
region = var.aws_region
}
terraform {
required_version = ">= 0.15"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 3.20.0"
}
}
backend "s3" {
key = "tfstates/productname"
bucket = "name-of-bucket"
region = "region"
}
}