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