erre/local_actions/generate-host-number.py

62 lines
1.8 KiB
Python
Raw Normal View History

#!/usr/bin/env python
import os
import argparse
import sys
import yaml
BASE_DIR='generated_vars/networking'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate local vars for networking.')
parser.add_argument('netname', metavar='netname', type=str, help='the netname')
parser.add_argument('hostname', metavar='hostname', type=str, help='the hostname')
args = parser.parse_args()
NET_DIR = os.path.join(BASE_DIR, args.netname)
HOST_PATH = os.path.join(NET_DIR, args.hostname)
if not os.path.exists(NET_DIR):
os.makedirs(NET_DIR)
if os.path.exists(HOST_PATH):
with open(HOST_PATH, 'r') as f:
host_number = int(f.read())
print host_number
f.close()
else:
host_number = 0
defined_hosts = [f for f in os.listdir(NET_DIR) if os.path.isfile(os.path.join(NET_DIR, f))]
for host in defined_hosts:
with open(os.path.join(NET_DIR, host), 'r') as f:
ip = int(f.read())
if ip > host_number:
host_number = ip
f.close()
host_number += 1
with open(HOST_PATH, 'w') as f:
f.write(str(host_number))
f.close()
print host_number
host_vars_dir = 'host_vars/'
if not os.path.exists(host_vars_dir):
os.makedirs(host_vars_dir)
host_file = os.path.join(host_vars_dir, args.hostname)
if os.path.exists(host_file):
with open(host_file, 'rw+') as f:
data = yaml.load(f)
f.close()
os.remove(host_file)
else:
data = {}
data[args.netname] = { 'host_number': host_number }
with open(host_file, 'w') as f:
f.write(yaml.dump(data, explicit_start=True, default_flow_style=False))
f.close()