Skip to content

Instantly share code, notes, and snippets.

@micw
Last active January 23, 2024 16:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micw/d7c0e34aee751e81c5aa952b29b8631b to your computer and use it in GitHub Desktop.
Save micw/d7c0e34aee751e81c5aa952b29b8631b to your computer and use it in GitHub Desktop.
Python script to replace ${PLACEHOLDER} in config files with content from environment variables
#!/usr/bin/env python
#
# Replaces ${placeholder} in a config file by it's corresponding environment variable.
# Fails if a variable is missing.
#
# The latest version of this script can be found at https://gist.github.com/micw/d7c0e34aee751e81c5aa952b29b8631b
#
import argparse,re
from os import environ
from sys import exit
missing_vars=[]
verbose = False
def replace_var(match):
var=match.group(1)
if verbose:
print " * Found placeholder ${%s}" % (var)
if var in environ:
return environ[var]
missing_vars.append(var)
return ""
def main():
parser = argparse.ArgumentParser(description='Replace placeholders in config.')
parser.add_argument('configfile', metavar='CONFIGFILE', help='Configfile to parse')
parser.add_argument('outputfile', metavar='OUTPUTFILE', nargs='?', help='Optional output file. If ommitted, the configfile is overwritten')
parser.add_argument('-v', action='store_true', help='Verbose')
args = parser.parse_args()
infile=args.configfile
outfile=args.outputfile if args.outputfile else infile
global verbose
verbose=args.v
if verbose:
print "Processing placeholders in %s" % infile
with open(infile, 'r') as instream:
content = instream.read()
content=re.sub("\${(.*?)}",replace_var,content)
if len(missing_vars)>0:
print
print "Error processing %s:" % infile
for missing_var in missing_vars:
print " * Missing environment variable: %s" % missing_var
print
exit(1)
if verbose:
print " * Writing changes to %s" % outfile
with open(outfile, 'w') as outstream:
outstream.write(content)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment