Last active
October 17, 2023 16:08
-
-
Save stefan-matic/fb0edd37df419420c6360a1993ccbd5f to your computer and use it in GitHub Desktop.
Quick and easy script to create an S3 bucket and dynamodb for the Terraform S3 backend. Run the script without parameters to create everything (e.g. ./init-terraform-backend.sh) or call each function individually if you want to do step-by-step (e.g ./init-terraform-backend create_terraform_s3_bucket).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Edit these variables: | |
# Make sure that the PROJECT is something unique, | |
# since the s3 bucket name needs to be globally unique | |
export PROJECT="YOUR_PROJECT" | |
export AWS_REGION="YOUR_REGION" | |
export BUCKET="${PROJECT}-terraform-state-files" | |
export LOCK_TABLE="${PROJECT}-terraform-locks" | |
create_terraform_s3_bucket() { | |
aws s3api create-bucket \ | |
--region "${AWS_REGION}" \ | |
--bucket "${BUCKET}" \ | |
--create-bucket-configuration LocationConstraint="${AWS_REGION}" | |
aws s3api put-bucket-versioning \ | |
--bucket "${BUCKET}" \ | |
--versioning-configuration MFADelete=Disabled,Status=Enabled | |
aws s3api put-bucket-encryption \ | |
--region "${AWS_REGION}" \ | |
--bucket "${BUCKET}" \ | |
--server-side-encryption-configuration \ | |
'{"Rules": [{"BucketKeyEnabled": true}]}' | |
} | |
create_terraform_dynamodb_locks_table() { | |
aws dynamodb create-table \ | |
--region "${AWS_REGION}" \ | |
--table-name "${LOCK_TABLE}" \ | |
--attribute-definitions AttributeName=LockID,AttributeType=S \ | |
--key-schema AttributeName=LockID,KeyType=HASH \ | |
--billing-mode PAY_PER_REQUEST | |
} | |
create_terraform_backend_tf() { | |
cat > backend.tf <<EOF | |
terraform { | |
backend "s3" { | |
bucket = "${BUCKET}" | |
key = "${PROJECT}.tfstate" | |
region = "${AWS_REGION}" | |
dynamodb_table = "${LOCK_TABLE}" | |
} | |
} | |
EOF | |
} | |
create_terraform_provider_tf() { | |
cat > provider.tf <<EOF | |
provider "aws" { | |
region = "${AWS_REGION}" | |
} | |
EOF | |
} | |
# Check if a function name is provided as a command line argument | |
if [ $# -eq 1 ]; then | |
case "$1" in | |
create_terraform_s3_bucket) | |
create_terraform_s3_bucket | |
;; | |
create_terraform_dynamodb_locks_table) | |
create_terraform_dynamodb_locks_table | |
;; | |
create_terraform_backend_tf) | |
create_terraform_backend_tf | |
;; | |
create_terraform_provider_tf) | |
create_terraform_provider_tf | |
;; | |
*) | |
echo "Invalid function name provided" | |
;; | |
esac | |
else | |
create_terraform_s3_bucket | |
create_terraform_dynamodb_locks_table | |
create_terraform_backend_tf | |
create_terraform_provider_tf | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment