lxd-project/lxd_interface.py

56 lines
1.9 KiB
Python
Raw Permalink Normal View History

import time
2022-11-23 18:55:06 +00:00
import pylxd
import ipaddress
2022-11-23 18:55:06 +00:00
lxd_client = pylxd.client.Client()
2022-11-26 22:24:31 +00:00
def create_instance(container_name: str, instance_password: str):
2022-11-23 18:55:06 +00:00
config = {'name': container_name, 'source':
{'type': 'image', "mode": "pull", "server": "https://cloud-images.ubuntu.com/daily", "protocol": "simplestreams",
'alias': 'lts/amd64'}, 'config': {'security.nesting': 'true'}}
2022-11-23 18:55:06 +00:00
instance = lxd_client.instances.create(config, wait=True)
instance.start(wait=True)
while type(ipaddress.ip_address(instance.state().network['eth0']['addresses'][0]['address'])) != ipaddress.IPv4Address:
time.sleep(0.1)
2022-11-26 22:24:31 +00:00
setup_ssh(container_name, instance_password)
return instance.state().network['eth0']['addresses'][0]
2022-11-23 18:55:06 +00:00
def destroy_instance(container_name: str):
instance = lxd_client.instances.get(container_name)
instance.stop(wait=True)
instance.delete(wait=True)
return True
2022-11-28 19:38:07 +00:00
def destroy_all_instances():
for instance in lxd_client.instances.all():
instance.stop(wait=True)
instance.delete(wait=True)
return True
2022-11-26 22:24:31 +00:00
def execute_command(container_name: str, command: list, stdin_payload=None):
instance = lxd_client.instances.get(container_name)
2022-11-26 22:24:31 +00:00
result_tuple = instance.execute(command, stdin_payload=stdin_payload)
return result_tuple
2022-11-26 22:24:31 +00:00
def setup_ssh(container_name: str, instance_password: str):
execute_command(container_name,
["sed", "-i", "s/PasswordAuthentication no/PasswordAuthentication yes/", "/etc/ssh/sshd_config"])
execute_command(container_name,
["sed", "-i", "s/#PermitRootLogin prohibit-password/PermitRootLogin yes/",
"/etc/ssh/sshd_config"])
execute_command(container_name, ["systemctl", "restart", "sshd"])
execute_command(container_name, ["passwd", "root"], stdin_payload=f"{instance_password}\n{instance_password}")
return True