autonode/createvm.py
2024-06-10 10:57:29 +10:00

75 lines
2.6 KiB
Python

import argparse
import yaml
from autonode import proxmox as pve
from autonode import cobbler as cobbler
def load_config(config_path="config.yaml"):
"""
Load configuration from YAML file.
"""
with open(config_path, "r") as file:
return yaml.safe_load(file)
def parse_arguments():
"""
Parse command-line arguments.
"""
parser = argparse.ArgumentParser(description="Create a VM in Proxmox and register it in Cobbler.")
parser.add_argument("--vcpu", type=int, choices=range(1, 17), help="Number of virtual CPUs")
parser.add_argument("--mem", type=int, choices=range(1, 33), help="Memory in GB")
parser.add_argument("--disk0", default="32", help="Size of disk0 in GB")
parser.add_argument("--disk1", type=int, help="Size of disk1 in GB")
parser.add_argument("--pool", help="Disk pool name")
parser.add_argument("--net0", help="Bridge name for net0")
parser.add_argument("--ip", help="IPAddress name for net0")
parser.add_argument("--gw", help="Gateway for net0")
parser.add_argument("--interface", help="Interface name, e.g. eth0 or enp0s2")
parser.add_argument("--bios", choices=["bios", "uefi"], help="BIOS or UEFI")
parser.add_argument("--role", help="Management class in Cobbler")
parser.add_argument("--domain", help="Domain name for host")
return parser.parse_args()
def main():
config = load_config()
args = parse_arguments()
# define vm details by merging config and arguments
details = {
'mem': args.mem or config['defaults']['mem'],
'vcpu': args.vcpu or config['defaults']['vcpu'],
'disk0': args.disk0 or '32',
'disk1': args.disk1 or None,
'pool': args.pool or config['defaults']['pool'],
'net0': args.net0 or config['defaults']['net0'],
'ip': args.ip,
'gw': args.gw,
'interface': args.interface or config['defaults']['interface'],
'bios': args.bios or config['defaults']['bios'],
'domain': args.bios or config['defaults']['domain'],
}
# Initialise the proxmox connection
proxmox = pve.connect_proxmox(config)
# Find the next available VMID
vmid = pve.find_next_vmid(proxmox)
# Generate the VM name
vmname = pve.generate_vm_name(proxmox, vmid, details)
# Find the best host to create the VM on
node = pve.find_node_for_vm(proxmox, details)
# Create the VM and save the macaddress
mac_address = pve.create_vm(proxmox, node, config, details, vmid, vmname)
# Create system in Cobbler
cobbler.create_system(mac_address, config, details, vmname)
# Start the VM
pve.start_vm(proxmox, node, vmid)
if __name__ == "__main__":
main()