🔒 This directory contains the Terraform configuration for setting up and managing the S3 backend used for storing the state of our cloud infrastructure securely.
- ✨ Utilization of the cloudposse/tfstate-backend/aws module for robust backend setup.
- 🗄️ Secure storage of Terraform state in an S3 bucket.
- 🔒 DynamoDB table for state locking to prevent concurrent state modifications.
- Direnv for loading environment variables.
- Terraform for infrastructure provisioning.
- TFswitch to switch between Terraform versions easily.
-
Change Directory:
Navigate to the directory containing the Terraform configuration:
cd live/terraform-backend
-
Create .envrc file:
Create a new
.envrc
file in this directory by copying the.envrc.example
file:cp .envrc.example .envrc
Then, update the
.envrc
file with the values for your environment! -
Load Environment Variables:
Load the environment variables using
direnv
:direnv allow
-
Set Terraform Version:
Ensure you are using the correct Terraform version:
tfswitch
-
Initialize Terraform:
Initialize the working directory with the required providers and modules:
terraform init -backend-config="./configs/${ENVIRONMENT}-backend.tfvars"
-
Workspace Management:
Select or create a new workspace tailored to your deployment environment:
# Select an existing workspace terraform workspace select "${TF_WORKSPACE}" # Create a new workspace if it doesn't exist and select it terraform workspace new "${TF_WORKSPACE}"
🚀 Deployment Instructions:
-
Plan Your Deployment:
Review and verify the deployment plan:
terraform plan -var-file "./configs/${ENVIRONMENT}.tfvars" -out "${ENVIRONMENT}.tfplan"
-
Execute the Plan:
Apply the planned configuration to provision the infrastructure:
terraform apply "${ENVIRONMENT}.tfplan"
🚀 NOTE: Confirm the actions before proceeding to ensure that the correct resources are being created or modified.
If this is your first deployment, Terraform will prompt you to confirm the setup of the backend. This is a critical step as it involves creating resources that will handle your Terraform state.
-
Initiate Backend Transfer:
If migrating from a local state, use the following command to migrate the state to the S3 bucket safely:
terraform init -backend-config="./configs/${ENVIRONMENT}-backend.tfvars" -force-copy
Push the changes to your version control system:
git add s3-backend.tf && git commit -m "Setup Terraform S3 backend" git push
To remove the backend infrastructure, you can run the following command. Be cautious as this will remove the S3 bucket and the DynamoDB table used for state locking:
terraform destroy -var-file "./configs/${ENVIRONMENT}.tfvars"
- Security Best Practices: Ensure that the S3 bucket and DynamoDB table have strict access policies to protect your state files.
- Documentation: Keep documentation up to date and ensure all team members are aware of the backend configurations and how to handle state files securely.