config/utils: YAML: Use C bindings if available
[pharos.git] / config / utils / generate_config.py
1 #!/usr/bin/python
2 ##############################################################################
3 # Copyright (c) 2018 OPNFV and others.
4 #
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"""
11
12 import argparse
13 import logging
14 import os
15 from subprocess import CalledProcessError, check_output
16 import gen_config_lib
17 import yaml
18 from jinja2 import Environment, FileSystemLoader
19
20
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
26
27 ENV = Environment(loader=FileSystemLoader(os.path.dirname(ARGS.jinja2)))
28 gen_config_lib.load_custom_filters(ENV)
29
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
32 try:
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.')
38 except OSError as ex:
39     logging.warn('eyaml not found, skipping decryption. Fallback to raw data.')
40 try:
41     DICT['details']
42 except (NameError, TypeError) as ex:
43     with open(ARGS.yaml) as _:
44         DICT = yaml.load(_, Loader=LOADER)
45
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']
52
53 # Print dictionary generated from yaml (uncomment for debug)
54 # print(DICT)
55
56 # Render template and print generated conf to console
57 TEMPLATE = ENV.get_template(os.path.basename(ARGS.jinja2))
58
59 # pylint: disable=superfluous-parens
60 print(TEMPLATE.render(conf=DICT))