2 ##############################################################################
3 # Copyright (c) 2018 OPNFV and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10 """Generate configuration from PDF/IDF and jinja2 installer template"""
14 from os.path import abspath, exists, isfile, split
15 from subprocess import CalledProcessError, check_output
18 from jinja2 import Environment, FileSystemLoader
21 LOADER = yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader
23 PARSER = argparse.ArgumentParser()
24 PARSER.add_argument("--yaml", "-y", type=str, required=True)
25 PARSER.add_argument("--jinja2", "-j", type=str, required=True, action='append')
26 PARSER.add_argument("--includesdir", "-i", action='append', default=['/'])
27 PARSER.add_argument("--batch", "-b", action='store_true')
28 PARSER.add_argument("--verbose", "-v", action='count')
29 ARGS = PARSER.parse_args()
31 ARGS.jinja2 = [abspath(x) for x in ARGS.jinja2]
34 LOGGER = logging.getLogger('generate_config')
36 LOGGER.setLevel(logging.INFO)
39 loader=FileSystemLoader(ARGS.includesdir),
40 extensions=['jinja2.ext.do']
42 gen_config_lib.load_custom_filters(ENV)
44 # Run `eyaml decrypt` on the whole file, but only if PDF data is encrypted
45 # Note: eyaml return code is 0 even if keys are not available
47 if isfile(ARGS.yaml) and 'ENC[PKCS7' in open(ARGS.yaml).read():
48 DICT = yaml.load(check_output(['eyaml', 'decrypt',
49 '-f', ARGS.yaml]), Loader=LOADER)
50 except CalledProcessError as ex:
51 LOGGER.error('eyaml decryption failed! Fallback to raw data.')
53 LOGGER.warn('eyaml not found, skipping decryption. Fallback to raw data.')
56 except (NameError, TypeError) as ex:
57 with open(ARGS.yaml) as _:
58 DICT = yaml.load(_.read().replace('/', '__slash__'), Loader=LOADER)
60 # If an installer descriptor file (IDF) exists, include it (temporary)
61 IDF_PATH = '/idf-'.join(split(ARGS.yaml))
63 with open(IDF_PATH) as _:
64 IDF = yaml.load(_, Loader=LOADER)
65 DICT['idf'] = IDF['idf']
67 # Print dictionary generated from yaml (uncomment for debug)
70 for _j2 in ARGS.jinja2:
71 TEMPLATE = ENV.get_template(_j2)
72 OUTPUT = TEMPLATE.render(conf=DICT).replace('__slash__', '/')
73 # Render template and write generated conf to file or stdout
75 if _j2.endswith('.j2'):
76 destination_file = _j2[:-3] # Trim '.j2' suffix
77 LOGGER.info('Parsing {}'.format(_j2))
78 with open(destination_file, 'w') as _:
81 LOGGER.warn('Skipping {}, name does not end in ".j2"'.format(_j2))
83 # pylint: disable=superfluous-parens