This scenario shows:
- how to use backend and save Terraform state file on S3
Code: https://github.com/omerbsezer/Fast-Terraform/blob/main/labs/backend-remote-state/
- You should have a look following lab:
-
With enabling remote state file using backend:
- multiple user can work on the same state file
- saving common state file on S3 is possible
-
Create S3 bucket on AWS
- Create basic main.tf file.
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
backend "s3" {
bucket = "terraform-state"
key = "key/terraform.tfstate"
region = "eu-central-1"
}
}
provider "aws" {
region = "eu-central-1"
}
resource "aws_instance" "instance" {
ami = "ami-0d1ddd83282187d18" # Ubuntu 22.04 eu-central-1 Frankfurt
instance_type = "t2.nano"
tags = {
Name = "Basic Instance"
}
}
Code: https://github.com/omerbsezer/Fast-Terraform/blob/main/labs/backend-remote-state/main.tf
- Run init, validate command:
terraform init
terraform validate
- Run plan, apply command:
terraform plan # for dry-run
terraform apply
- On AWS S3, tfstate file is created:
- On local machine, state file is not saved now:
- On AWS, state file can be viewed, downloaded:
- With pull command, state file can be download on local machine:
terraform state pull > terraform.tfstate
- Run destroy command:
terraform destroy
- After destroy command, all resources are deleted in state file on S3:
- To download updated state file:
terraform state pull > terraform.tfstate