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"""
15 from subprocess import CalledProcessError, check_output
18 from jinja2 import Environment, FileSystemLoader
21 PARSER = argparse.ArgumentParser()
22 PARSER.add_argument("--yaml", "-y", type=str, required=True)
23 PARSER.add_argument("--jinja2", "-j", type=str, required=True)
24 ARGS = PARSER.parse_args()
25 LOADER = yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader
27 ENV = Environment(loader=FileSystemLoader(os.path.dirname(ARGS.jinja2)))
28 gen_config_lib.load_custom_filters(ENV)
30 # Run `eyaml decrypt` on the whole file, but only if PDF data is encrypted
31 # Note: eyaml return code is 0 even if keys are not available
33 if os.path.isfile(ARGS.yaml) and 'ENC[PKCS7' in open(ARGS.yaml).read():
34 DICT = yaml.load(check_output(['eyaml', 'decrypt',
35 '-f', ARGS.yaml]), Loader=LOADER)
36 except CalledProcessError as ex:
37 logging.error('eyaml decryption failed! Fallback to raw data.')
39 logging.warn('eyaml not found, skipping decryption. Fallback to raw data.')
42 except (NameError, TypeError) as ex:
43 with open(ARGS.yaml) as _:
44 DICT = yaml.load(_, Loader=LOADER)
46 # If an installer descriptor file (IDF) exists, include it (temporary)
47 IDF_PATH = '/idf-'.join(os.path.split(ARGS.yaml))
48 if os.path.exists(IDF_PATH):
49 with open(IDF_PATH) as _:
50 IDF = yaml.load(_, Loader=LOADER)
51 DICT['idf'] = IDF['idf']
53 # Print dictionary generated from yaml (uncomment for debug)
56 # Render template and print generated conf to console
57 TEMPLATE = ENV.get_template(os.path.basename(ARGS.jinja2))
59 # pylint: disable=superfluous-parens
60 print(TEMPLATE.render(conf=DICT))