Skip to content

Instantly share code, notes, and snippets.

@qpwo
Created October 3, 2024 00:59
Show Gist options
  • Save qpwo/6a95daf51ffa3417936d509a54a8c646 to your computer and use it in GitHub Desktop.
Save qpwo/6a95daf51ffa3417936d509a54a8c646 to your computer and use it in GitHub Desktop.
vagrant wrapper thing to make it a one-off create/destroy thingy
import os
from pathlib import Path
import json
import shutil
# 192.168.122.#{i+150}
template = """
Vagrant.configure("2") do |config|
config.vm.box = "debian/bookworm64"
# provider config
config.vm.provider "libvirt" do |v|
v.memory = 512
v.cpus = 1
end
config.ssh.keys_only = false
config.ssh.insert_key = false
config.vm.synced_folder ".", "/vagrant", disabled: true
# Basic setup through a shell provisioner
config.vm.provision "shell", inline: <<-SHELL
mkdir -p /root/.ssh
echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGyUQZ/RFZZKS4q0zbp7OKWa/ly34CUshbkm8BEJ3/B/ FORLOCALTESTONLY" >> /root/.ssh/authorized_keys
SHELL
config.vm.provision :shell, :inline => "sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config; sudo systemctl restart sshd;", run: "always"
config.vm.provision :shell, :inline => "sudo sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/g' /etc/ssh/sshd_config; sudo systemctl restart sshd;", run: "always"
config.vm.provision "shell", path: "init.sh"
config.vm.define "{name}" do |node|
node.vm.network "private_network", ip: "{ip}"
node.vm.hostname = "{name}"
end
end
"""
root = Path("~/vagrs").expanduser()
def make_vm(name: str, ip: str, script_path: None | str | Path):
d = root / name
assert not d.exists(), f"{d} already exists"
d.mkdir(parents=True)
with open(d / "Vagrantfile", "w") as f:
f.write(template.format(name=name, ip=ip))
with open(d / "data.json", "w") as f:
json.dump({"name": name, "ip": ip}, f)
if script_path is None:
with open(d / "init.sh", "w") as f:
f.write("echo doing nothing")
else:
script_path = Path(script_path)
shutil.copy(script_path, d / "init.sh")
os.system(f"cd {d.absolute()} && vagrant up")
# make_vm("coolvm", "192.168.122.155", "myscript.sh")
# ssh-keygen -f "/home/ubuntu/.ssh/known_hosts" -R "192.168.122.155"
# ssh -i ~/.ssh/LOCAL_TEST_id_ed25519 [email protected]
# get_ip("coolvm")
# delete_vm("coolvm")
def delete_vm(name: str):
d = root / name
assert d.exists(), f"{d} does not exist"
os.system(f"cd {d.absolute()} && vagrant destroy -f")
shutil.rmtree(d)
def get_ip(name: str):
d = root / name
assert d.exists(), f"{d} does not exist"
with open(d / "data.json") as f:
return json.load(f)["ip"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment