Link to this headingTerraform

https://github.com/antonputra/tutorials/tree/main/lessons/196/terraform

Link to this headingBackends

  • Local: Lock file on the current machine
  • Terraform Cloud: Per user cost from company
  • AWS S3: Self managed S3 bucket with database for concurrency checks

Link to this headingAWS S3

Steps:

  1. Initially don’t set a backend so it uses the local backend.
  2. Then change your terraform script to use the backend that you just created to manage terraform
  3. Run terraform init again to update the correct backend

Auto manage backend through terraform:

# Setup Local Backend for bootstrapping terraform { ############################################################# ## AFTER RUNNING TERRAFORM APPLY (WITH LOCAL BACKEND) ## YOU WILL UNCOMMENT THIS CODE THEN RERUN TERRAFORM INIT ## TO SWITCH FROM LOCAL BACKEND TO REMOTE AWS BACKEND ############################################################# # backend "s3" { # bucket = "devops-directive-tf-state" # REPLACE WITH YOUR BUCKET NAME # key = "03-basics/import-bootstrap/terraform.tfstate" # region = "us-east-1" # dynamodb_table = "terraform-state-locking" # encrypt = true # } required_providers { aws = { source = "hashicorp/aws" version = "~> 3.0" } } } provider "aws" { region = "us-east-1" } #Setup S3 Backend for resource "aws_s3_bucket" "terraform_state" { bucket = "devops-directive-tf-state" # REPLACE WITH YOUR BUCKET NAME force_destroy = true } resource "aws_s3_bucket_versioning" "terraform_bucket_versioning" { bucket = aws_s3_bucket.terraform_state.id versioning_configuration { status = "Enabled" } } resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state_crypto_conf" { bucket = aws_s3_bucket.terraform_state.bucket rule { apply_server_side_encryption_by_default { sse_algorithm = "AES256" } } } resource "aws_dynamodb_table" "terraform_locks" { name = "terraform-state-locking" billing_mode = "PAY_PER_REQUEST" hash_key = "LockID" attribute { name = "LockID" type = "S" } }

Link to this headingCommon Commands

Example setup:

#Setup AWS CLI aws configure #Setup Teraform terraform init && terraform plan terraform apply #Clean up when finished terraform destroy