我正在尝试使用Vagrant和Chef-Client配置来处理我正在进行的任务。我希望能够在使用vagrant up
时生成唯一名称,将实例加入Chef服务器,然后在完成时删除该节点。我有这个主要工作;当我运行Chef Destroy时,我坚持从Chef Server自动删除节点。我需要找到一种方法来缓存名称并在以后检索它,只运行vagrant up
的主机名配置,或者我还没想到的一些选项。
我的vagrantfile的片段如下:
Vagrant.configure('2') do |config|
config.vm.box = 'centos/6'
config.vm.hostname = "vagrant-#{SecureRandom.hex(2)}-el6.dev.local"
config.vm.provision 'chef_client' do |chef|
chef.chef_server_url = 'https://chef.dev.local/organizations/foo'
chef.add_role 'build_vm'
chef.node_name = config.vm.hostname
chef.delete_node = true
chef.delete_client = true
end
end
当它在vagrant up
运行时,主机名设置为vagrant-229b-el6.dev.local
但在销毁时它会尝试销毁vagrant-3a1c-el6.dev.local
。它显然在每次运行时运行config.vm.hostname
行,所以合乎逻辑的是不要让它发生。如果vagrant up
创建的主机名仍然存在,那么我需要做什么才能让Chef知道以后删除它?
答案 0 :(得分:3)
您不能仅使用Vagrantfile执行此操作。我认为,Vagrantfile是在每个流浪汉运行时读取的,所以每次它生成另一个随机名称。您可以做的是在第一次运行时将生成的主机名保存到环境变量或文件中,并在下次运行时从那里读取它,然后删除文件或取消设置vagrant destroy
上的env变量。
这可以通过Vagrantfile本身内部的简单ruby代码来完成,例如:
# We save the hostname into '.vagrant_hostname' file.
VAGRANT_HOSTNAME = '.vagrant_hostname'
if File.exist? VAGRANT_HOSTNAME
hostname = IO.read( VAGRANT_HOSTNAME ).strip
else
hostname = "vagrant-#{SecureRandom.hex(2)}-el6.dev.local"
IO.write( VAGRANT_HOSTNAME, hostname )
end
Vagrant.configure('2') do |config|
[...]
config.vm.hostname = hostname
[...]
end
if <the command is "vagrant destroy">
File.delele VAGRANT_HOSTNAME
end