Skip to content

Latest commit

 

History

History
118 lines (76 loc) · 2.91 KB

LAB11-Backend-Remote-State.md

File metadata and controls

118 lines (76 loc) · 2.91 KB

LAB-11: Backend - Remote States => Provision EC2 and Save State File on S3

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/

Prerequisite

Steps

  • 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

image

image

  • 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

image

  • Run init, validate command:
terraform init
terraform validate

image

  • Run plan, apply command:
terraform plan   # for dry-run
terraform apply
  • On AWS S3, tfstate file is created:

image

  • On local machine, state file is not saved now:

image

  • On AWS, state file can be viewed, downloaded:

image

  • With pull command, state file can be download on local machine:
terraform state pull > terraform.tfstate

image

  • Run destroy command:
terraform destroy
  • After destroy command, all resources are deleted in state file on S3:

image

  • To download updated state file:
terraform state pull > terraform.tfstate