Automatically generate a node_name for Chef

This is required because the Chef Server almost always needs a node name to
interact. This will default to the hostname, but that's always going to be
`vagrant.vm`, which will collide easily.

This generates a random hostname with `vagrant-` as the prefix and stores the
result in the machine's data directory.
This commit is contained in:
Seth Vargo 2015-11-19 11:25:34 -08:00
parent fd3e1ff592
commit 9559fc549c
4 changed files with 40 additions and 5 deletions

View File

@ -19,6 +19,22 @@ module VagrantPlugins
super
@logger = Log4r::Logger.new("vagrant::provisioners::chef")
if @config.node_name.to_s.empty?
cache = @machine.data_dir.join("chef_node_name")
if !cache.exist?
@machine.ui.info I18n.t("vagrant.provisioners.chef.generating_node_name")
cache.open("w+") do |f|
f.write("vagrant-#{SecureRandom.hex(4)}")
end
end
if cache.file?
@logger.info("Loading cached node_name...")
@config.node_name = cache.read.strip
end
end
end
def install_chef
@ -123,7 +139,7 @@ module VagrantPlugins
end
def setup_json
@machine.env.ui.info I18n.t("vagrant.provisioners.chef.json")
@machine.ui.info I18n.t("vagrant.provisioners.chef.json")
# Get the JSON that we're going to expose to Chef
json = @config.json
@ -154,7 +170,7 @@ module VagrantPlugins
remote_file = guest_encrypted_data_bag_secret_key_path
return if !remote_file
@machine.env.ui.info I18n.t(
@machine.ui.info I18n.t(
"vagrant.provisioners.chef.upload_encrypted_data_bag_secret_key")
@machine.communicate.tap do |comm|

View File

@ -31,8 +31,13 @@ module VagrantPlugins
end
def cleanup
delete_from_chef_server('node') if @config.delete_node
delete_from_chef_server('client') if @config.delete_client
if @config.delete_node
delete_from_chef_server("node")
end
if @config.delete_client
delete_from_chef_server("client")
end
end
def create_client_key_folder

View File

@ -1931,6 +1931,8 @@ en:
"The cookbook path '%{path}' doesn't exist. Ignoring..."
json: "Generating chef JSON and uploading..."
client_key_folder: "Creating folder to hold client key..."
generating_node_name: |-
Auto-generating node name for Chef...
install_failed: |-
Vagrant could not detect Chef on the guest! Even after Vagrant
attempted to install Chef, it could still not find Chef on the system.

View File

@ -5,11 +5,23 @@ require Vagrant.source_root.join("plugins/provisioners/chef/provisioner/base")
describe VagrantPlugins::Chef::Provisioner::Base do
include_context "unit"
let(:machine) { double("machine") }
let(:iso_env) do
# We have to create a Vagrantfile so there is a root path
env = isolated_environment
env.vagrantfile("")
env.create_vagrant_env
end
let(:machine) { iso_env.machine(iso_env.machine_names[0], :dummy) }
let(:config) { double("config") }
subject { described_class.new(machine, config) }
before do
allow(config).to receive(:node_name)
allow(config).to receive(:node_name=)
end
describe "#encrypted_data_bag_secret_key_path" do
let(:env) { double("env") }
let(:root_path) { "/my/root" }