From 8e6cd999112fa2a44cf5084f960f400241189f29 Mon Sep 17 00:00:00 2001 From: Bogdan Matei <132910112+bmatei-visma@users.noreply.github.com> Date: Fri, 29 Sep 2023 16:35:02 +0300 Subject: [PATCH] feat: extend tf.sh to be able to work with the backend (AC-9451) (#8) --- README.md | 20 ++++++++++++++++++++ tf.sh | 24 ++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/README.md b/README.md index 68bf27d..bc0f9a4 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ stacks/ backend.tf <...> +state-management/ The directory for the backend of your workspaces and stacks + <...> accounts Mapping between workspace names and AWS accounts backend.tf Global terraform backend file. Will be copied or symlinked in each stack global.tf Global terraform file. Will be copied or symlinked in each stack @@ -104,6 +106,24 @@ Do some stuff: ``apply`` always use ``-auto-approve=false``. In an automation scenario, use ``./tf.sh apply -auto-approve=true`` +# Managing your backend + +Command usage `tf.sh backend ` + +## Initzialization +How to create the backend: +* run `terraform init && terraform apply` locally +* run `tf.sh backend init -migrate-state` + * if you don't have the local state anymore you'll have to import the resources manually + * check [here](https://developer.hashicorp.com/terraform/cli/import) for more information +* any plan applies needs to use the following syntax `tf.sh backend ` (e.g. plan/applu/etc..) + +## Subsequent modifications +Switching between workspaces: +* run `tf.sh workspace ` +* run `tf.sh backend init` + + # Dependency graph ``tf deps`` will generate a graph in the dot language to show dependencies between stacks. diff --git a/tf.sh b/tf.sh index ac49f7e..963abe3 100755 --- a/tf.sh +++ b/tf.sh @@ -57,6 +57,26 @@ function setup_workspace { fi } +function backend { + if [ -z $TF_USE_CURRENT_PROFILE ] + then + export AWS_PROFILE=$TERRAFORM_WORKSPACE + fi + + echo "Using directory 'state-management'" + cd $DIR/state-management + cp $DIR/backend.tf backend.symlink.tf + + BACKEND_BUCKET="terraform-state-${accounts[${TERRAFORM_WORKSPACE}]}" + STATE_KEY_ID=$(aws kms list-aliases --query "Aliases[?AliasName==\`alias/terraform-state\`].{keyid:TargetKeyId}" --output text) + if [ "$1" == "init" ]; then + rm -rf .terraform terraform.tfstate.d .terraform.lock.hcl + $TERRAFORM_BIN $1 ${@:2} -backend-config="bucket=${BACKEND_BUCKET}" -backend-config="key=backend/terraform.tfstate" -backend-config="encrypt=true" -backend-config="kms_key_id=${STATE_KEY_ID}" + else + $TERRAFORM_BIN $@ + fi +} + function init_workspace { if [ -z $TF_USE_CURRENT_PROFILE ] then @@ -429,6 +449,10 @@ case $TF_COMMAND in init_workspace exit $? ;; + backend) + backend $@ + exit $? + ;; *) (>&2 echo -e "${RED}Command $TF_COMMAND is unsupported! Use terraform $TF_COMMAND at your own risks...${NC}") exit 1;