Home > database >  How to create s3 bucket beckend and remote state with terragrunt
How to create s3 bucket beckend and remote state with terragrunt

Time:01-04

Hello mates i am new to terraform and terragrunt and i wanna to create s3 bucked in my code and lockID with dynamoDB for my tfstate but i don't know how to do it all in terragrunt i know how to create them manually and then create a backend but no idea how to do it in my code can you help me mates i looked over the documentetion but can't find anything there maybe its my falt i know but if someone can help me with this one i will be greatfull.

I tried this from the documentation

generate "backend" {
  path      = "backend.tf"
  if_exists = "overwrite_terragrunt"
  contents = <<EOF
terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "${path_relative_to_include()}/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "my-lock-table"
  }
}
EOF
}

but this only works only if the s3 is created manualy i want everithing to be created automaticaly with one command but i am having dificulties with this one for terragrunt specificaly.

CodePudding user response:

When you init, terraform looks for a state file so that your cloud infrastructure and your IAC code can be on the same page. In that case, if you declare backend bucket it will try to look into it. Otherwise will throw error. So yes it has to be created beforehand. But, there is another way if we are talking about automation -

  • install aws cli in your machine (which should already be done)
  • make a bash script to create a bucket (or) then run terraform init apply etc..
!/bin/bash

aws s3 mb s3://state-bucket

# little time for the bucket to be created
sleep 20 
terraform init

But remember the purpose of IAC and Automation is not to automate everything, the state bucket is meant to be never deleted nor changed manually. And you should not destroy it either.

Note: you can't destroy non empty buckets.

Best wishes.

  • Related