6adbb44efdf4ab6878fbea815c10575158f51db0
[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
26 ENV = Environment(
27     loader=FileSystemLoader(os.path.dirname(ARGS.jinja2)),
28     extensions=['jinja2.ext.do']
29 )
30 gen_config_lib.load_custom_filters(ENV)
31
32 # Run `eyaml decrypt` on the whole file, but only if PDF data is encrypted
33 # Note: eyaml return code is 0 even if keys are not available
34 try:
35     if os.path.isfile(ARGS.yaml) and 'ENC[PKCS7' in open(ARGS.yaml).read():
36         DICT = yaml.safe_load(check_output(['eyaml', 'decrypt',
37                                             '-f', ARGS.yaml]))
38 except CalledProcessError as ex:
39     logging.error('eyaml decryption failed! Fallback to raw data.')
40 except OSError as ex:
41     logging.warn('eyaml not found, skipping decryption. Fallback to raw data.')
42 try:
43     DICT['details']
44 except (NameError, TypeError) as ex:
45     with open(ARGS.yaml) as _:
46         DICT = yaml.safe_load(_)
47
48 # If an installer descriptor file (IDF) exists, include it (temporary)
49 IDF_PATH = '/idf-'.join(os.path.split(ARGS.yaml))
50 if os.path.exists(IDF_PATH):
51     with open(IDF_PATH) as _:
52         IDF = yaml.safe_load(_)
53         DICT['idf'] = IDF['idf']
54
55 # Print dictionary generated from yaml (uncomment for debug)
56 # print(DICT)
57
58 # Render template and print generated conf to console
59 TEMPLATE = ENV.get_template(os.path.basename(ARGS.jinja2))
60
61 # pylint: disable=superfluous-parens
62 print(TEMPLATE.render(conf=DICT))