Vagrant Giveth Chef Nodes Vagrant Taketh Chef Nodes Away

2012-10-10

At work we are in the process of cleaning up some technical debt and redoing out infrastructure. Part of this is rolling out Chef for managing our machines. While doing this I have been using Vagrant as a test bed for working with new cookbooks and testing out new services. This works great wether you run chef local with Vagrant or with a Chef server. One bit of frustration I ran into while using a Chef server was that Vagrant wouldn’t delete the Chef node from the server. This was a problem because whenever I would destroy a Vagrant instance and then rebuild it I would get a Chef error about the node already existing. It’s an easy problem to solve just run.

knife client delete NODE
knife node delete NODE

However, I am lazy and don’t want to have to do that each time I delete a Vagrant box. Instead, I figured out how to modify my Vagrantfile so when I run destroy it will also run those commands. All you have to do to add this functionally is add the following lines to the bottom of your Vagrantfile.

module Vagrant
  module Provisioners
    class ChefClient
      def cleanup
        puts "Deleting client: #{config.node_name}"
        puts `sh -c 'knife client delete #{config.node_name} -y'`
        puts "Deleting node: #{config.node_name}"
        puts `sh -c 'knife node delete #{config.node_name} -y'`
      end
    end
  end
end

Now with that added to your Vagrantfile whenever you run

vagrant destroy

your Vagrant box, Chef client and Chef node instance will get deleted and you can rebuild error-free.