-
-
Save arbabnazar/f249c82c0a64e23b19f1a4743406d986 to your computer and use it in GitHub Desktop.
Vagrant triggers for updating host hosts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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