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