Skip to content

Instantly share code, notes, and snippets.

@mbaitelman
Last active August 4, 2020 16:34
Show Gist options
  • Save mbaitelman/5cf28e9cab7455c1cd4a8db913fa9888 to your computer and use it in GitHub Desktop.
Save mbaitelman/5cf28e9cab7455c1cd4a8db913fa9888 to your computer and use it in GitHub Desktop.
Reloading PATH for Chef on Windows

Reloading PATH for Chef on Windows

Many times when installing applications on Windows the path gets updated but Chef doesnt have the updated path. When the application gets called it cant find the application in path and the step fails.

Add the refreshenv.rb file to the libraries folder and notifies and ruby_block to the resource that needs reloading.

This code is from https://stackoverflow.com/a/49993683 and is based on the Chocolatey code

directory 'c:\Java' do
action :create
end
file 'c:\java\java.settings.cfg' do
content 'INSTALL_SILENT=Enable
AUTO_UPDATE=Disable
WEB_JAVA=Enable
WEB_ANALYTICS=Disable
EULA=Disable
REBOOT=Disable'
end
windows_package 'Java' do
action :install
source 'C:\Java\javainstall.exe'
installer_type :custom
options '/s INSTALLCFG=c:/java/java.settings.cfg'
notifies :run, 'ruby_block[refreshenv]', :immediately
end
ruby_block 'refreshenv' do
block do
refresh_env
end
action :nothing
end
# Copied from https://stackoverflow.com/a/49993683
require 'win32/registry' if Chef::Platform.windows?
def get_reg_env(hkey, subkey, &block)
Win32::Registry.open(hkey, subkey) do |reg|
reg.each_value do |name|
value = reg.read_s_expand(name)
ENV[name] = if block && ENV.key?(name)
yield(name, ENV[name], value)
else
value
end
end
end
end
def refresh_env
get_reg_env(Win32::Registry::HKEY_LOCAL_MACHINE, 'System\CurrentControlSet\Control\Session Manager\Environment')
get_reg_env(Win32::Registry::HKEY_CURRENT_USER, 'Environment') do |name, old_value, new_value|
if name.upcase == 'PATH'
old_value || File::PATH_SEPARATOR || new_value
else
new_value
end
end
end
# $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment