-
Notifications
You must be signed in to change notification settings - Fork 0
/
write_hardware_jsons.py
104 lines (82 loc) · 2.66 KB
/
write_hardware_jsons.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import ipaddress
import uuid
import sys
import json
def write_hardware_json(ip_address, gateway, netmask, MAC, uuid):
##### ip
ip = {}
ip['address'] = str(ip_address)
ip['gateway'] = gateway
ip['netmask'] = netmask
#### dhcp
dhcp = {}
dhcp['arch'] = 'x86_64'
dhcp['ip'] = ip
dhcp['mac'] = MAC
dhcp['uefi'] = False
#### netboot
netboot = {}
netboot['allow_pxe'] = True
netboot['allow_workflow'] = True
### interfaces
interfaces = []
interfaces.append({})
### facility
facility = {}
facility['facility_code'] = 'onprem'
### interfaces 1
interfaces[0]['dhcp'] = dhcp
interfaces[0]['netboot'] = netboot
## network
network = {}
network['interfaces'] = interfaces
## metadata
metadata = {}
metadata['facility'] = facility
metadata['instance'] = {}
metadata['state'] = ''
# hardware_data
hardware_data = {}
hardware_data['id'] = uuid
hardware_data['metadata'] = metadata
hardware_data['network'] = network
print(json.dumps(hardware_data, indent=2))
def main():
# Command line arguments
# 1. gateway
# 2. CIDR string
# 3. MAC address file
# Parse command line arguments
NUM_CMD_LINE_ARGUMENTS = 3
if((len(sys.argv) - 1) != NUM_CMD_LINE_ARGUMENTS):
print('Invalid command line argument') # TODO Print help here
exit(1)
else:
gateway = sys.argv[1]
CIDR_string = sys.argv[2]
MAC_address_file_path = sys.argv[3]
# Create CIDR object and check it is valid else exit
try:
CIDR = ipaddress.ip_network(CIDR_string)
netmask = str(ipaddress.IPv4Network(CIDR).netmask)
except ValueError:
print('Invalid CIDR: %s Did you set the host bits?' % CIDR_string)
exit(1)
# Read MACs from input file to list
f = open(MAC_address_file_path, "r", encoding="utf-8")
MACS = f.read().splitlines()
ip_counter = 0
# Iterate through MACs in input file until no more MACs or no more IP space in subnet
for MAC in MACS:
try:
write_hardware_json(CIDR[ip_counter], gateway, netmask, MAC, str(uuid.uuid4()))
ip_counter += 1
except IndexError as ex:
print("Cannot allocate IP for %s on line %s. Insufficient IP space in range: %s" % (MAC, ip_counter+1, CIDR_string))
print(ex)
f.close()
exit(1)
# Close file handle if we enoutered no exceptions
f.close()
if __name__ == "__main__":
main()