Executing Windows Batch Script in Chef

Similar to Linux script resources for bash, ruby, and so on, Chef can execute arbitrarily-defined Windows batch scripts through the command interpreter. When these resources are used, Chef compiles the contents of the batch script as defined in the resource block’s code attribute and then deposits it on the managed host and it is executed from there.

Take caution when using script resources; they are unstructured and can easily perform actions that have unintended side effects. Similar to the
way the software is built, two immediate subsequent runs of the Chef client on a node should have the same effect as only running it once in
order to guarantee a reliable and consistent system configuration. Make sure that you develop scripts that are idempotent in nature (that is, it
can be run multiple times and have the same effect as only running once), or use conditionals to prevent multiple executions.

Since scripts are arbitrary and of a free form, you can use them to achieve anything that you cannot model using the existing resources. However, care must be taken to prevent repeated execution that would cause negative side effects. One way to avoid performing potentially destructive actions is to use the not_if and only_if conditions to prevent multiple executions. That being said, if you find that you are performing the same type of action repeatedly, consider writing a custom resource and provider if possible.

Note: Chef 11.6.0 and upwards includes a built-in batch resource; use windows_batch when implementing an earlier Chef version.

When running a batch script on a Windows host using earlier versions of Chef, the windows_batch resource can be used. The following table shows the available actions and parameters when using the windows_batch resource:

Example of batch scripts

In the following code, we will look at how we might build a command to execute rsync with some parameters specified using the node attributes:

windows_batch 'synchronize_files' do
 code <<-EOH
 rsync.exe -a -v -z #{node[:rsyncserver]} #{node[:rsyncdest]}
 EOH
end 

Alternatively, one might want to execute a Ruby script on the node as follows:

windows_batch 'execute_some_ruby' do
 cwd "C:/Temp"
 code "C:\Ruby210\ruby.exe C:\Temp\run_me.rb"
end 

Venky Jayaraman

20+ years of extensive expertise developing and managing enterprise level application. 7+ years of extensive experience building and implementing Bigdata solution.