Skip to content

Instantly share code, notes, and snippets.

@arbabnazar
Forked from mgsisk/Vagrantfile
Created December 29, 2022 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arbabnazar/f249c82c0a64e23b19f1a4743406d986 to your computer and use it in GitHub Desktop.
Save arbabnazar/f249c82c0a64e23b19f1a4743406d986 to your computer and use it in GitHub Desktop.
Vagrant triggers for updating host hosts
Vagrant.configure('2') do |config|
ENV['HOST'] ||= '_ sys._'
config.vm.box = 'debian/contrib-buster64'
config.vm.hostname = File.basename(Dir.pwd) + '.test'
config.vm.network 'private_network', type: 'dhcp'
config.trigger.after :reload, :resume, :up do |trig|
trig.info = 'Updating sytstem hosts...'
trig.ruby do |env, vm|
hostname = `vagrant ssh #{vm.name} -c 'hostname -f' -- -q`.chomp
ip_address = `vagrant ssh #{vm.name} -c 'hostname -I | cut -d " " -f 2' -- -q`.chomp
system("echo '#{ip_address} #{ENV['HOST'].gsub('_', hostname)} # vagrant-#{vm.id}' | sudo tee -a /etc/hosts >/dev/null") unless Vagrant::Util::Platform.windows?
if Vagrant::Util::Platform.windows?
require 'win32ole'
hFile = File.expand_path('system32/drivers/etc/hosts', ENV['windir'])
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute("echo #{ip_address} #{ENV['HOST'].gsub('_', hostname)} # vagrant-#{vm.id}>> #{hFile}", nil, nil, 'runas')
end
end
end
config.trigger.before :destroy, :reload do |trig|
delete_hosts(trig)
end
config.trigger.after :halt, :suspend do |trig|
delete_hosts(trig)
end
end
def delete_hosts(trig)
trig.info = 'Updating system hosts...'
trig.ruby do |env, vm|
system("sudo sed -i '' '/ # vagrant-#{vm.id}$/d' /etc/hosts") unless Vagrant::Util::Platform.windows?
if Vagrant::Util::Platform.windows?
require 'win32ole'
hFile = File.expand_path('system32/drivers/etc/hosts', ENV['windir'])
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute("findstr /v /c:\" # vagrant-#{vm.id}$\" #{hFile} >> #{hFile}", nil, nil, 'runas')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment