deploy_aldpro/deploy_aldpro_vm.py

91 lines
2.8 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
import subprocess
from pprint import pprint
import yaml
with open('vars.yaml') as data:
vars_dict = yaml.safe_load(data)
def check_vm(id):
"""
Проверка существования ВМ.
:param id: (int), идентификатор ВМ.
:return: None
"""
proc = subprocess.run(f'qm status {id}'.split(), capture_output=True, text=True)
if not proc.stderr:
print(f'Вероятно ВМ с идентификатором - {id} уже существует')
print(proc.stderr)
exit(1)
def shell_run(cmd):
"""
Выполнение shell команды.
:param cmd: (str), команда.
:return: proc.stdout: (subprocess object), вывод команды
proc.stderr: (subprocess object), код завершения.
"""
proc = subprocess.run(
cmd.split(), capture_output=True, text=True, timeout=60)
if proc.stderr:
print(f'Команда - "{cmd}"')
print(proc.stderr)
exit(1)
return proc.stdout, proc.stderr
def gen_vm_commands(all_dict):
"""
Генерация списка команд для создания группировки ВМ ALD Pro.
:param all_dict: (dict), словарь с переменными для генерации.
:return: (dict), словарь списков команд.
"""
tmpl_id = all_dict['template']['id']
gw = all_dict['proxmox_node']['vmbr_gw']
commands = {}
for vm in vars_dict['vms']:
vm_cmds = [f'qm clone {tmpl_id} {vm["id"]} --name {vm["name"]} --full',
f'qm set {vm["id"]} --ipconfig0 ip={vm["ip"]}/24,gw={gw}',
f'qm resize {vm["id"]} scsi0 32G']
if vm["name"] == 'dc01' or vm["name"] == 'dc02':
vm_cmds.append(f'qm set {vm["id"]} --cores 4 --memory 8192')
vm_cmds.remove(f'qm resize {vm["id"]} scsi0 32G')
vm_cmds.append(f'qm resize {vm["id"]} scsi0 64G')
elif vm["name"] == 'repo':
vm_cmds.remove(f'qm resize {vm["id"]} scsi0 32G')
vm_cmds.append(f'qm resize {vm["id"]} scsi0 64G')
commands.update({vm["name"]: vm_cmds})
return commands
def create_vms(commands_dict):
"""
Создание группировки ВМ ALD Pro.
:param commands_dict: (dict), словарь списков команд для создания ВМ.
:return: None
"""
for role in commands_dict.items():
print(f'Создаётся ВМ - {role[0]}')
for cmd in role[1]:
shell_run(cmd)
if __name__ == "__main__":
ids = [vars_dict['template']['id']]
for id in vars_dict['vms']['id']:
ids.append(id)
for id in ids:
check_vm(id)
cmds = gen_vm_commands(vars_dict)
create_vms(cmds)
# pprint(cmds)