Skip to content

Instantly share code, notes, and snippets.

@prelegalwonder
Created March 30, 2020 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prelegalwonder/448ee7f0a1e246744f83661b89feed5e to your computer and use it in GitHub Desktop.
Save prelegalwonder/448ee7f0a1e246744f83661b89feed5e to your computer and use it in GitHub Desktop.
TF - Ansible Vault External Datasource
#!/usr/bin/env python
import string,sys,os,types
import json
from ansible_vault import Vault
def readPass(passFile):
try:
file = open(passFile, 'r')
contents = file.read()
cleaned = contents.strip('\n')
return cleaned
except EOFError as ex:
print("Caught the EOF error.")
raise ex
except IOError as ex:
print("Caught the I/O error.")
raise ex
passFile = sys.argv[1]
vaultFile = sys.argv[2]
param = sys.argv[3].split('.')
paramLen = len(param)-1
passwd = readPass(passFile)
vault = Vault(passwd)
data = vault.load(open(vaultFile).read())
for val in param:
if val in data and param.index(val) != paramLen :
data = data.pop(val)
else:
if not isinstance(data[val], str) and len(data[val]) > 1:
print(json.dumps(data[val]))
else:
newdict = {}
newdict[val] = data[val]
print(json.dumps(newdict))
@prelegalwonder
Copy link
Author


## Due to a limitation of TF Schema, we have to specify separate datasources for each section since they're maps and not strings.
## Reference: https://github.com/terraform-providers/terraform-provider-external/issues/2

data "external" "db_secrets" {
  program = ["${path.module}/tfvault.py", "vpass", "${path.module}/tfvars/${terraform.workspace}-vault.yml", "database"]
}

data "external" "google_secrets" {
  program = ["${path.module}/tfvault.py", "vpass", "${path.module}/tfvars/${terraform.workspace}-vault.yml", "google"]
}

etc..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment