Disable Windows Server firewall with PowerShell in Chef

First of all, as I said in the previous post, be aware that is a very BAD practice to disable the firewall; do so only for test purposes and a short period of time.

The following code was tested under Windows Server 2008 R2, but it should also work for Windows Server 2012.
In the default.rb file from the recipe subfolder of your cookbook, add the code:

require ‘chef/win32/version’
win_version = Chef::ReservedNames::Win32::Version.new

if (win_version.windows_server_2008_r2? ||
    win_version.windows_server_2008? ||
    win_version.windows_server_2003_r2? ||
    win_version.windows_server_2003? ||
    win_version.windows_2000?)
      disableFirewallScript =<<-EOH
        netsh advfirewall set allprofiles state off
      EOH
elsif (win_version.windows_server_2012_r2? ||
    win_version.windows_server_2012?)
      disableFirewallScript =<<-EOH
        Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
      EOH
else
  raise “Unsupported Windows version !”
end

Chef::Log.debug(“Executing ' #{disableFirewallScript} ' in PowerShell.”)

disableFirewallResult = powershell_out(disableFirewallScript)

if (disableFirewallResult.stderr.to_s != “” || disableFirewallResult.exitstatus != 0)
  raise “ExitStatus : #{disableFirewallResult.exitstatus} \r\n STDOUT : [ #{disableFirewallResult.stdout} ] \r\n STDERR : [ #{disableFirewallResult.stderr} ]”
end

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: