Last active
November 17, 2023 16:58
-
-
Save jurno/cfa9ab572d2e37e07c11facc7b5409d5 to your computer and use it in GitHub Desktop.
Terraform Cloud statefile backup
This file contains hidden or 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 | |
| # Odzalohuje vsetky statefiles z organization v Terraform Cloud. Skript predpoklada, | |
| # ze pouzivatel je prihlaseny do Terraform Cloud cez `terraform login` a takto ziskany | |
| # token ma ulozeny defaultnym sposobom. | |
| # https://www.terraform.io/cli/commands/login#credentials-storage | |
| # Pouzitie: | |
| # chmod +x ./backup-terraform-cloud.sh | |
| # ./backup-terraform-cloud.sh <ORGANIZATION> | |
| if [ -z $1 ] | |
| then | |
| echo "[ERROR] Musis zadat nazov TFC organization ako parameter." | |
| echo " Napriklad: ./backup-terraform-cloud.sh azure-sandbox-pd" | |
| echo "" | |
| exit 1 | |
| fi | |
| TOKEN=$(cat ~/.terraform.d/credentials.tfrc.json | jq -r '.[]."app.terraform.io".token') | |
| ORG_NAME=$1 | |
| YEAR=$(date +"%Y") | |
| MONTH=$(date +"%m") | |
| DIR=$(date +"%y%m%d-%H%M") | |
| BACKUP_DIR=$YEAR/$MONTH/$DIR/$ORG_NAME | |
| mkdir -p $BACKUP_DIR | |
| WORKSPACE_ID=$(curl \ | |
| -H "Authorization: Bearer $TOKEN" \ | |
| -H "Content-Type: application/vnd.api+json" \ | |
| "https://app.terraform.io/api/v2/organizations/$ORG_NAME/workspaces" | jq -r '.data [].id') | |
| for ID in $WORKSPACE_ID; do | |
| OBJECT_ID=$(curl \ | |
| -H "Authorization: Bearer $TOKEN" \ | |
| -H "Content-Type: application/vnd.api+json" \ | |
| "https://app.terraform.io/api/v2/workspaces/$ID/current-state-version" | jq -r '.data.attributes."hosted-state-download-url"') | |
| curl -L -H "Authorization: Bearer $TOKEN" "$OBJECT_ID" -o $BACKUP_DIR/$ID.tfstate | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment