terraform, aws,

Terraform ./init.sh script for AWS backend state

Jun 09, 2022 · 1 min read · Post a comment

terraform init initialize the current Terraform working directory. I guess it does a lot under the hood which unfortunately won’t be the topic for today. Instead, I’ll share with you a bash script that could help with initializing the TF backend stored on AWS.


  • Terraform


Managing Terraform state with AWS is done by saving the state file in an encrypted and versioned S3 bucket and locking is managed by a DynamoDB table. You might want to create these two resources beforehand thus, leading to a chicken-egg problem (correct me if I’m wrong) where initially the TF state will be stored on your local machine. Now, there’s a bunch of posts online you could look for on how to do the setup properly, so once you got that figured out, take a look at the following script that I’ve found and modified a bit to fit my requirements:


# Usage: ./init.sh once to initialize remote storage for this environment.
# Subsequent tf actions in this environment don't require re-initialization, 
# unless you have completely cleared your .terraform cache.
# terraform plan  -var-file=./prod.tfvars 
# terraform apply -var-file=./prod.tfvars 


terraform init \
    -backend-config="bucket=$TF_VAR_s3_bucket" \
    -backend-config="key=$TF_VAR_state_file" \
    -backend-config="dynamodb_table=$TF_VAR_dynamodb_lock" \
    -backend-config="region=$TF_VAR_aws_region" \

echo "set remote s3 state to $TF_ENV.tfstate"


Feel free to share any ideas or improvements over the given example above. On a side note, follow our official channel on Telegram.