Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

prelegalwonder commented Mar 30, 2020


## 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
You can’t perform that action at this time.