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.
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:
#!/bin/bash # 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 TF_VAR_s3_bucket="devcoops-tf-state" TF_VAR_state_file="devcoops.tfstate" TF_VAR_dynamodb_lock="devcoops-tf-state-lock" TF_VAR_aws_region="eu-west-1" 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" \ -backend-config="encrypt=true" 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.