Search code examples
rubyformatchef-infradriveknife

chef run a command just one time


working on a chef recipe and I need to format a drive before mounting it and I did it like this:

execute "Format drive" do
   command "mkfs.ext4 /dev/xvde1"
   end

and then I used another command to mount it in /var/log/ All worked fine but now the problem is that when I run the recipe a second time the mkfs.ext4 fails because the drive is mounted.. and it should fail :)

My question is how can I run this mkfs.ext4 command on the node only the first time and not every time after that?

Or how can I force chef to not stop when this particular command fails (not and elegant solution though)

Or is there another ruby command that is used for specifically formatting drives? (longshot)

A a workaround solution I found is to add the format command at the end of this file /opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.10.4/lib/chef/knife/bootstrap that I've notice runs only when creating the server for the first time but I would like to do this the proper way.


Solution

  • You can add a not_if statement to do a check and see if it has already been mounted so it won't attempt to do it again. Something like this:

    execute "Format drive" do
      command "mkfs.ext4 /dev/xvde1"
      not_if  "grep xvde1 /proc/mounts"
    end
    

    There is also only_if for cases when you want to do something only if some other criteria has been met.