in infra/build/developer-tools/build/scripts/export_tf_outputs.py [0:0]
def main(args):
"""Utility to pipe outputs from one terraform configuration to another.
Parses outputs of applied terraform configuration and prints them as
TF_VAR_{name}={value} to be later supplied to another terraform
configuration
"""
# If path to terraform doesn't exist, notify and gracefully exit
if not os.path.exists(args.path):
script = "#!/usr/bin/env bash\n"
script += ("echo 'Warning: Folder not found: %s"
) % args.path
print(script)
sys.exit(0)
# Get terraform outputs and parse them from json.
terraform_command = "cd %s && terraform output -json"
outputs_json = os.popen(terraform_command % args.path).read()
outputs = json.loads(outputs_json)
# If the specified folder was not a terraform configuration or if it was not
# provisioned, terraform just silently ignores it and returns an empty object.
# Notify user about this and exit.
if not outputs:
script = "#!/usr/bin/env bash\n"
script += ("echo 'Warning: The terraform state file at %s either has no "
"outputs defined, or the terraform configuration has not"
"been provisioned yet.'"
) % args.path
print(script)
sys.exit(0)
# process value of each variable
variables = {}
plain_types = (int, float, "".__class__, u"".__class__)
for name in outputs:
if isinstance(outputs[name]['value'], plain_types):
variables[name] = outputs[name]['value']
else:
variables[name] = json.dumps(outputs[name]['value'])
# Generate a bash script which exports TF_VAR`s
script = "#!/usr/bin/env bash\n"
script += "echo 'Automatically setting inputs from outputs of %s'\n" % args.path
for name in variables:
script += "export TF_VAR_%s='%s'\n" % (name, variables[name])
# Handle the magic `sa_key` variable in a special way
if 'sa_key' in variables:
service_account = get_service_account(variables['sa_key'])
script += "export SERVICE_ACCOUNT_JSON='%s'" % service_account
# Output to stdout
print(script)