Skip to content

Instantly share code, notes, and snippets.

@cristim
Created June 25, 2020 21:24
Show Gist options
  • Save cristim/8cf10ab407ad96770f152805d1a41616 to your computer and use it in GitHub Desktop.
Save cristim/8cf10ab407ad96770f152805d1a41616 to your computer and use it in GitHub Desktop.
Dump Terraform Cloud Workspace variables into a terraform.auto.tfvars file

Getting Started

Virtualenv setup

pip install virtualenvwrapper
mkvirtualenv tfe2tfvars
workon tfe2tfvars
pip install -r requirements.txt

Usage

The following command will generate a terraform.auto.tfvars file in the current directory populated with the values taken from the Terraform workspace variables:

./tfe2tfvars.py -t tfe_hostname -o tfe_org -w workspace
pyhcl
requests
terrasnek
#!/usr/bin/env python3
import argparse
import os
import sys
import hcl
from terrasnek.api import TFC
def read_args():
parser = argparse.ArgumentParser(
description='''
Read variables from a Terraform Cloud or Terraform Enterprise Workspace
and dump them into a new terraform.auto.tfvars file.
It automatically reads the TFE Token from ~/.terraformrc
''')
parser.add_argument('-t', '--tfe-hostname', help='TFE Hostname',
default='app.terraform.io')
parser.add_argument('-o', '--organization', help='TFE Organization')
parser.add_argument('-w', '--workspace', help='TFE Workspace')
parser.add_argument('-f', '--output-file', help='Output file',
default='terraform.auto.tfvars')
args = parser.parse_args()
if args.organization is None:
print('Missing Organization, pass the -o|--organization command-line flag')
sys.exit(1)
if args.workspace is None:
print('Missing workspace, pass the -w|--workspace command-line flag')
sys.exit(1)
return args
def get_tfe_token(hostname):
with open(os.path.expanduser('~/.terraformrc'), 'r') as fp:
obj = hcl.load(fp)
return obj['credentials'][hostname]['token']
def output_tfvars(vars, file):
with open(file, 'w') as fp:
for obj in vars['data']:
key = obj['attributes']['key']
value = obj['attributes']['value']
fp.write('%s = %s\n' % (key, value))
def main():
args = read_args()
token = get_tfe_token(args.tfe_hostname)
api = TFC(token, url="https://"+args.tfe_hostname)
api.set_org(args.organization)
vars = api.vars.list(args.workspace)
output_tfvars(vars, args.output_file)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment