import sys import os import shutil from itertools import islice def copy(src, dst, rename): try: shutil.copyfile(src, dst) if rename is False: print("[DEBUG]", "Copied file from %s to %s." % (src, dst)) else: print("[DEBUG]", "Renamed file from %s to %s." % (src, dst)) except shutil.SameFileError: print("Source and destination represents the same file.") except IsADirectoryError: print("Destination is a directory.") except PermissionError: print("Permission denied.") except Exception as e: print(e) print("Error occured while copying file.") p = '.\configuration\slo\\' for file in os.listdir(p): fn_content = file.split(".") vars = {} with open(os.path.join(p,file)) as f: i = 0 firstLine = f.readline() meta = firstLine.split() for line in f: multiline = "" #check for key value pair if " = " in line: try: if "<<-EOT" in line: multiline = "<<-EOT\n" skipped = islice(f,i,None) for i, l in enumerate(skipped): if "EOT" not in l: multiline = multiline + l else: multiline = multiline + l break name,var = line.partition(" = ")[::2] var.strip() if multiline != "": var = multiline #remove spaces and "#" as this is used for optional fields vars['"{' + name.strip().lstrip("#").strip() + '}"'] = var vars["{ResourceName}"] = meta[2].replace('"','') except Exception as e: print(e) i = i + 1 copy('./templates/service-level-objective.tf','./output/slo/service-level-objective.tf',False) os.rename('.\output\slo\service-level-objective.tf','./output/slo/' + meta[2].replace('"','') + '.tf') with open('./output/slo/' + meta[2].replace('"','') + '.tf') as tf: data = tf.read() for key,var in vars.items(): #print(key,var) data = data.replace(key, var) with open('./output/slo/' + meta[2].replace('"','') + '.tf','w+') as tf: tf.write(data) tf_command = "terraform.exe import module." + meta[2].replace('"','') + ".dynatrace_slo.main " + fn_content[1] print(tf_command)