Share your chef's knife.rb config with vagrant
We use Chef Server for our provisioning and we use Vagrant for local development and testing. But why should I configure my chef provisioning two times? Wouldn't it be nice to have a project specific knife.rb
which vagrant can use? Here it is.
knife.rb
My knife.rb
usually contains some logging config and the chef configuration. You can add your cloud api keys here as well.
# Logging.
log_level :debug
log_location STDOUT
# Chef server configuration.
chef_server_url "#{ENV['KNIFE_CHEF_SERVER']}"
client_key "#{ENV['KNIFE_CLIENT_KEY']}"
node_name "#{ENV['KNIFE_NODE_NAME']}"
validation_client_name "#{ENV['KNIFE_VALIDATION_CLIENT_NAME']}"
validation_key "#{ENV['KNIFE_VALIDATION_CLIENT_KEY']}"
The knife.rb
gets the necessary data from environment variables. This way I can safely commit the knife.rb
to my DVCS and it doesn't collide with my coworkers configs.
Environment variables
You can add the environment variables to your .profile
or .bash_profile
:
# Opscode chef configurations.
export KNIFE_CHEF_SERVER="https://chef-api.example.com"
export KNIFE_CLIENT_KEY="$HOME/.chef/client.pem"
export KNIFE_NODE_NAME="myclient"
export KNIFE_VALIDATION_CLIENT_NAME="chef-validator"
export KNIFE_VALIDATION_CLIENT_KEY="$HOME/.chef/chef-validator.pem"
Vagrantfile
Now it's time to add some code to your Vagrantfile
. On the very top, add those two lines:
require 'chef'
Chef::Config.from_file(File.join(File.dirname(__FILE__), '.chef', 'knife.rb'))
This will load the chef configuration from the knife.rb
located in your projects .chef
directory.
The chef server provisioning for your vagrant box then might look like this:
config.vm.provision :chef_client do |chef|
chef.chef_server_url = Chef::Config[:chef_server_url]
chef.log_level = Chef::Config[:log_level]
chef.validation_key_path = Chef::Config[:validation_key]
chef.validation_client_name = Chef::Config[:validation_client_name]
run_list = ['role[base]']
end
That's it. I now can use one knife.rb
config for both my local vagrant machines as well as for production use.
Written by Thomas Massmann
Related protips
2 Responses
Does not appear to be working with the current versions of Chef (11.4.4), Vagrant (1.2.2), and rbenv. Vagrant reports:
Vagrant failed to initialize at a very early stage:
There was an error loading a Vagrantfile. The file being loaded and the error message are shown below. This is usually caused by a syntax error.
Path: /Users/jeffbyrnes/Sites/aws-jb-chef/Vagrantfile
Message: cannot load such file -- chef
You need to run the following command for newer Vagrant versions:
$ vagrant plugin install chef