Skip to content

Instantly share code, notes, and snippets.

@mfuerstenau
Created June 27, 2024 09:29
Show Gist options
  • Save mfuerstenau/07f2106ab7e1f52ffff181bde7535cb3 to your computer and use it in GitHub Desktop.
Save mfuerstenau/07f2106ab7e1f52ffff181bde7535cb3 to your computer and use it in GitHub Desktop.
Vagrantfile um n Boxen mit gleichem existierenden Schlüssel zu erzeugen
# -*- mode: ruby -*-
# vi: set ft=ruby :
default_box = "rockylinux/9"
default_cpus = 2
default_mem = 1024
nodes = [
{
ip_addr: '192.168.56.10',
hostname: 'vagrant1',
forwarded_ports: [{guest: 80, host: 8080},{guest: 443, host: 8443}]
},
{
ip_addr: '192.168.56.11',
hostname: 'vagrant2',
forwarded_ports: [{guest: 80, host: 8081},{guest: 443, host: 8444}]
}
]
# Function to check whether VM was already provisioned
def provisioned?(vm_name='default', provider='virtualbox')
File.exist?(".vagrant/machines/#{vm_name}/#{provider}/action_provision")
end
# Function to provision SSH keys and configurations
def provision_ssh(vm, private_key_path, public_key_path)
vm.vm.provision "file", source: private_key_path, destination: "/home/vagrant/.ssh/vagrant_private"
public_key = File.read(public_key_path)
vm.vm.provision :shell, :inline => <<-SHELL
echo 'Provisioning ssh key.'
mkdir -p /home/vagrant/.ssh
chmod 700 /home/vagrant/.ssh
echo '#{public_key}' > /home/vagrant/.ssh/authorized_keys
chmod -R 600 /home/vagrant/.ssh/authorized_keys
echo 'Host 192.168.*.*' > /home/vagrant/.ssh/config
echo 'StrictHostKeyChecking no' >> /home/vagrant/.ssh/config
echo 'UserKnownHostsFile /dev/null' >> /home/vagrant/.ssh/config
chmod -R 600 /home/vagrant/.ssh/config
SHELL
end
Vagrant.configure("2") do |config|
nodes.each do |node|
config.ssh.insert_key = false
config.vm.define node[:hostname] do |node_config|
node_config.vm.box = !node[:box].nil? ? node[:box] : default_box
node_config.vm.network "private_network", ip: node[:ip_addr]
node_config.vm.hostname = node[:hostname]
if node.key?(:forwarded_ports)
node[:forwarded_ports].each do |forwarded_port|
node_config.vm.network "forwarded_port", guest: forwarded_port[:guest], host: forwarded_port[:host]
end
end
if provisioned?(node[:hostname])
node_config.ssh.private_key_path = [ "vagrant_private" ]
else
provision_ssh(node_config, 'vagrant_private', 'vagrant_public')
end
end
end
end
@mfuerstenau
Copy link
Author

Anmerkung: Schlüssel wird nach "up" provisioniert, etwaig existierende Schlüssel aus Config entfernt, Schlüssel könnte natürlich auch konfigurierbar geamcht werden.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment