简体   繁体   中英

VagrantFile execution on vagrant destroy

Every time you call vagrant up or vagrant destroy VagrantFile gets executed?

It's because I'm having the following problem. On vagrant up I configure the machine with the following parameters:

config.vm.provision "chef_client" do |chef|
    chef.node_name = 'living-dev-'+Time.new.strftime("%H%M%S")
    config.vm.hostname = chef.node_name
end

When I execute vagrant destroy the following code executes:

config.trigger.after :destroy do
    info "Attempting to remove node #{config.vm.hostname}"
    run "knife node show #{config.vm.hostname} -c c:/chef/knife.rb"
    if $?.to_i == 0
        info "Removing node #{config.vm.hostname}"
        "knife node delete #{config.vm.hostname} -y -c c:/chef/knife.rb"
    end
end

The config.vm.hostname that I obtain here is diferent that the one defined on chef, so I'm not able to remove the vm machine on chef server.

How I can solve it?

Yes, when you execute the vagrant command, it reads the whole Vagrantfile and puts in memory to know how to work with the machine. so in your case even the provisioning block is read (and executed), and then when you'll reboot the VM, the hostname will change

I believe you can find on SO questions about handling dynamic hostname, but basically you need to persist this information, so you'll need to write the hostname once it is defined in a file and then reads from this file

If File.exist?(".vagrant/machines/default/virtualbox/hostname")
  File.open(".vagrant/machines/default/virtualbox/hostname", "rb")
  hostname = File.read
else 
  hostname = 'living-dev-'+Time.new.strftime("%H%M%S")
  File.open(".vagrant/machines/default/virtualbox/hostname" ,'w') do |f|
    f.write "#{hostname}]"
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM