Perl script using the Terraform Cloud API to export workspaces, variables, and variable sets to JSON files.
During the review of a disaster recovery plan, we realized that we didn't have a record of the values we set for variables in Terraform Cloud workspaces. It would be difficult to recover from the accidental deletion of a Terraform Cloud workspace. This Perl script was quickly written to export information to JSON files using the Terraform Cloud API. The exported information includes workspaces, variables, and variable sets which covers most of what we need.
- Install tfc-ops.
tfc-dumpwas tested withtfc-opsversion 3.1.2. - Obtain a Terraform Cloud access token. Go to https://app.terraform.io/app/settings/tokens to create an API token.
- Set and export the environment variable ATLAS_TOKEN with the Terraform Cloud access token as its value (e.g., use a command like export ATLAS_TOKEN=terraform-cloud-access-token). Note that preceding the
exportcommand with a space may prevent the command from being stored in the shell history. Refer to the description of theHISTCONTROLshell variable in thebashman page for details. - To dump one workspace: tfc-dump.pl --org terraform-cloud-organization --workspace terraform-cloud-workspace-name
- To dump all workspaces in an organization: tfc-dump.pl --org terraform-cloud-organization --all
Two files are created for each Terraform Cloud workspace:
- workspace-name-workspace.json
- workspace-name-variables.json
Two files are created for each Terraform Cloud Variable Set:
- varset-variable-set-name.json
- varset-variable-set-name-variables.json
Spaces in the variable set name are replaced with hyphens (-).
The code assumes that all of the Terraform Cloud Variable Sets are contained within the first result page of 20 entries.
The image created by the Dockerfile will run tfc-dump and use Restic to back up the resulting files to a repository stored in a Backblaze B2 bucket.
- Copy
local.env.disttolocal.env. - Set the values for the variables contained in
local.env. - Obtain a Terraform Cloud access token. Go to https://app.terraform.io/app/settings/tokens to create an API token.
- Add the access token value to
local.env. - Create a Backblaze B2 bucket. Set the
File LifecycletoKeep only the last version. - Add the B2 bucket name to
RESTIC_REPOSITORYinlocal.env. - Obtain a Backblaze Application Key. Restrict its access to the B2 bucket you just created. Ensure the application key has these capabilities: deleteFiles, listBuckets, listFiles, readBuckets, readFiles, writeBuckets, writeFiles.
- Add the application key and secret to
local.envas the values ofB2_ACCOUNT_IDandB2_ACCOUNT_KEYrespectively. - Build the Docker image:
docker build --tag tfc-backup:latest . - Initialize the Restic repository (one time only):
docker run --env-file=local.env --env BACKUP_MODE=init tfc-backup:latest - Run the Docker image:
docker run --env-file=local.env tfc-backup:latest