Created
August 31, 2017 19:25
-
-
Save hartfordfive/f9e4d1ce3863d00f3a75b79c6331af12 to your computer and use it in GitHub Desktop.
Python script to convert container env blocks to config maps in Kubernetes configs
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
import json, argparse, sys, os, time | |
from os.path import basename | |
def getFileContents(filename): | |
with open(filename, 'r') as f: | |
return f.read() | |
def writeToFile(filename, contents): | |
file = open(filename, "w") | |
file.write(contents) | |
file.close() | |
def buildConfigMap(envVars, namespace, name): | |
configMap = { | |
"apiVersion": "v1", | |
"kind": "ConfigMap", | |
"metadata": { | |
"name": "{}-configmap-{}".format(namespace, name), | |
"namespace": namespace | |
}, | |
"data": {} | |
} | |
for e in envVars: | |
configMap["data"][e["name"]] = e["value"] | |
return configMap | |
def getCurrentTimeString(): | |
return time.strftime("%Y%m%d%H%M%S", time.gmtime(time.time())) | |
def createBackupFile(originalFile): | |
contents = getFileContents(originalFile) | |
fname = "{}.bak-{}".format(originalFile, getCurrentTimeString()) | |
writeToFile(fname, contents) | |
return fname | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-f", "--file", help="Path to the kubernetes deployment file", type=str) | |
args = parser.parse_args() | |
if args.file == "" or args.file == None: | |
print("Usage: python k8s-conver-env.py -n [K8S_NAMESPACE] -f [K8S_DEPLOYMENT_FILE_PATH]\n") | |
sys.exit(1) | |
inFilename = args.file.strip() | |
new_files_created = [] | |
try: | |
conf = json.loads(getFileContents(inFilename)) | |
except Exception, e: | |
print("Error parsing JSON K8s config: {}\n".format(str(e))) | |
sys.exit(1) | |
if 'metadata' not in conf or 'namespace' not in conf['metadata']: | |
print("Input kubernetes deployment config is invalid!\n") | |
sys.exit(1) | |
namespace = conf['metadata']['namespace'] | |
if 'spec' in conf and 'template' in conf['spec'] and 'spec' in conf['spec']['template'] and 'containers' in conf['spec']['template']['spec']: | |
# If the config is valid, then create a backup of the original config file | |
new_files_created.append(createBackupFile(inFilename)) | |
for c in conf['spec']['template']['spec']['containers']: | |
if 'env' in c: | |
# Write the individual config maps files for each container | |
confMapFilePath = "{}/{}-{}-{}.json".format(os.path.dirname(inFilename), "00-configmap", namespace, c["name"]) | |
new_files_created.append(confMapFilePath) | |
writeToFile(confMapFilePath, json.dumps(buildConfigMap(c['env'], namespace, c["name"]), indent=4, sort_keys=True)) | |
# Set the config map reference | |
c['envFrom'] = [{"configMapRef": {"name": "{}-configmap-{}".format(namespace, c["name"])}}] | |
# Delete the old environment variable block | |
del(c['env']) | |
# Overwrite the original input file with the new config | |
writeToFile(inFilename, json.dumps(conf, indent=4, sort_keys=True)) | |
print("The following files have been created:") | |
for f in new_files_created: | |
if f.find(".bak") >= 0: | |
print("\t -> {} (original backup)".format(f)) | |
else: | |
print("\t -> {}".format(f)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment