request-naming-generator/main.py

77 lines
2.5 KiB
Python

#!/usr/bin/env python
"""
Input: This script takes a csv file containing the campaign name as input as following:
attributes.csv
name
-----------------
NIRA_Denmark_2023
NIRA_France_2023
.
.
.
-----------------
Output: This script generates a terraform file for request naming rules. The terraform file is based on a template.
The input .csv file shall be stored within the default input directory.
Usage: python3 main.py
"""
import configparser
import csv
import jinja2
import logging
import pathlib
import re
FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('main')
logger.setLevel(logging.INFO)
config = configparser.ConfigParser()
config.read("config.ini")
DEFAULT_INPUT_PATH = pathlib.Path(config['PATHS']['Input']).absolute()
DEFAULT_OUTPUT_PATH = pathlib.Path(config['PATHS']['Output']).absolute()
DEFAULT_TEMPLATES_PATH = pathlib.Path(config['PATHS']['Templates']).absolute()
env = jinja2.Environment(loader=jinja2.FileSystemLoader(DEFAULT_TEMPLATES_PATH))
template = env.get_template("template.request_naming.j2")
def checkDirectories(DEFAULT_INPUT_PATH, DEFAULT_OUTPUT_PATH, DEFAULT_TEMPLATES_PATH):
for dir in [DEFAULT_INPUT_PATH, DEFAULT_OUTPUT_PATH, DEFAULT_TEMPLATES_PATH]:
try:
pathlib.Path.mkdir(dir)
logger.info("Directory created: %s", dir)
except FileExistsError:
logger.info("Directory already exists: %s", dir)
def renderFile(file, DEFAULT_OUTPUT_PATH):
logger.info("Generating files for: %s", str(pathlib.PurePath(file).name))
with open(file, newline='') as csvfile:
data = csv.DictReader(csvfile, delimiter=';')
for row in data:
requestName = re.search("\_(.*)\_", str(row["name"])).group(1).replace('_',' ')
content = template.render(CampaignName = row["name"],
RequestName = requestName)
filename = pathlib.PurePath.joinpath(DEFAULT_OUTPUT_PATH, str(row["name"]) + ".request_attribute.tf")
with open(filename, mode='w+', encoding="utf-8") as output:
output.write(content)
logger.info("Generated: %s", pathlib.PurePath(filename).name)
if __name__ == '__main__':
checkDirectories(DEFAULT_INPUT_PATH, DEFAULT_OUTPUT_PATH, DEFAULT_TEMPLATES_PATH)
logger.info("Using default input directory: %s", DEFAULT_INPUT_PATH)
files = sorted(pathlib.Path(DEFAULT_INPUT_PATH).glob("*.csv"))
for f in files:
logger.info("File found: %s", str(f))
renderFile(f, DEFAULT_OUTPUT_PATH)