New scripts for configs generation, based on jinja2
[joid.git] / ci / genMAASConfig.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 """
5 This script generates a maas deployer config based on lab config file.
6
7 Parameters:
8  -l, --lab      : lab config file
9 """
10
11 from optparse import OptionParser
12 from jinja2 import Environment, FileSystemLoader
13 import os
14 import yaml
15 from pprint import pprint as pp
16 import socket
17 import fcntl
18 import struct
19
20 #
21 # Parse parameters
22 #
23
24 parser = OptionParser()
25 parser.add_option("-l", "--lab", dest="lab", help="lab config file")
26 (options, args) = parser.parse_args()
27 labconfig_file = options.lab
28
29 #
30 # Set Path and configs path
31 #
32
33 # Capture our current directory
34 TPL_DIR = os.path.dirname(os.path.abspath(__file__))+'/config_tpl/maas_tpl'
35 HOME = os.environ['HOME']
36 USER = os.environ['USER']
37
38 #
39 # Prepare variables
40 #
41
42 # Prepare a storage for passwords
43 passwords_store = dict()
44
45 #
46 # Local Functions
47 #
48
49
50 def load_yaml(filepath):
51     """Load YAML file"""
52     with open(filepath, 'r') as stream:
53         try:
54             return yaml.load(stream)
55         except yaml.YAMLError as exc:
56             print(exc)
57
58
59 def get_ip_address(ifname):
60     """Get local IP"""
61     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
62     return socket.inet_ntoa(fcntl.ioctl(
63         s.fileno(),
64         0x8915,  # SIOCGIFADDR
65         struct.pack('256s', bytes(ifname.encode('utf-8')[:15]))
66     )[20:24])
67
68
69 #
70 # Config import
71 #
72
73 # Load scenario Config
74 config = load_yaml(labconfig_file)
75 config['opnfv']['spaces_dict'] = dict()
76 for space in config['opnfv']['spaces']:
77     config['opnfv']['spaces_dict'][space['type']] = space
78 config['os'] = {'home': HOME,
79                 'user': USER,
80                 'brAdmIP': get_ip_address(config['opnfv']['spaces_dict']
81                                                 ['admin']['bridge'])}
82
83 # pp(config)
84
85 #
86 # Transform template to bundle.yaml according to config
87 #
88
89 # Create the jinja2 environment.
90 env = Environment(loader=FileSystemLoader(TPL_DIR),
91                   trim_blocks=True)
92 template = env.get_template('deployment.yaml')
93
94 # Render the template
95 output = template.render(**config)
96
97 # Check output syntax
98 try:
99     yaml.load(output)
100 except yaml.YAMLError as exc:
101     print(exc)
102
103 # print output
104 print(output)