Last active
July 18, 2021 04:43
-
-
Save andgineer/17f90aaa02a7042232e32aed9c4bacca to your computer and use it in GitHub Desktop.
Load .env files and expends (substitute) vars https://sorokin.engineer/posts/en/jenkins_load_env_vars_with_expanding.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Loads a number of files listed in args: | |
python expand_vars.py file1 file2 ... | |
Expects line format like | |
key=value | |
Skips comments and empty lines. | |
Substitute vars $var / ${var} from system environment and from previous lines / files/ | |
Universal Python 2 / 3 module to use on any Jenkins agent. | |
""" | |
from __future__ import print_function | |
import os | |
import os.path | |
import sys | |
def expand_vars(file_name): | |
for line in open(file_name, "r"): | |
line = line.strip() | |
if not line or line.startswith("#"): | |
continue # skip comments and empty lines | |
key = line.split("=")[0] | |
value = os.path.expandvars("=".join(line.split("=")[1:])) | |
for quote in ['"', "'"]: | |
if value.startswith(quote) and value.endswith(quote): | |
value = value[1:-1] | |
break # do not remove nested quotes | |
os.environ[key] = value | |
print("%s=%s" % (key, value)) | |
if __name__ == "__main__": | |
for file_idx in range(1, len(sys.argv)): | |
expand_vars(sys.argv[file_idx]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment