Skip to content

Instantly share code, notes, and snippets.

@garyellis
Created April 6, 2018 07:42
Show Gist options
  • Save garyellis/e37b170119f7b658ca11e4b210da2182 to your computer and use it in GitHub Desktop.
Save garyellis/e37b170119f7b658ca11e4b210da2182 to your computer and use it in GitHub Desktop.
POC decrypting gpg files into a temporary shell environment context
#!/usr/bin/env python
import gnupg
# from dotenv import dotenv_values
import sh
import shlex
import os
from pprint import pprint
_proc_environ = os.environ.copy()
def gpg_decrypt(gpg_file):
"""
Decrypts the given input gpg file as a string
"""
gpg = gnupg.GPG()
with open(gpg_file) as f_stream:
#log.info('decrypting {}'.format(gpg_file))
decrypted_data = gpg.decrypt_file(f_stream)
return str(decrypted_data)
def shell_vars_str_to_dict(shell_vars_data):
"""
Returns the given shell vars string as a dictionary
"""
#log.info("Preparing shell variables")
shell_vars = dict(token.split('=',1) for token in shlex.split(shell_vars_data))
return shell_vars
def sh_command_env(command_env):
"""
Helper to prepare sh.Command _env dict
"""
cmd_env = command_env
cmd_env.update(_proc_environ)
return cmd_env
if __name__ == '__main__':
gpg_files = [
'.env.gpg',
'.env2.gpg'
]
for i in gpg_files:
secrets_env = shell_vars_str_to_dict(
gpg_decrypt(i)
)
print '==> {}'.format(i)
print '==> secrets env'
pprint(secrets_env)
print '==> proc env'
pprint(sh_command_env(secrets_env))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment