Search code examples
windowspuppettemp

Get Temp Directory on Windows using Puppet


I am trying to download a file using download_file module and want to save it to the temp directory. Is there a built in way to do this using Puppet without hard-coding it to C:\Windows\Temp.

download_file { "Download Flyway" :
    url                   => 'https://bintray.com/artifact/download/business/maven/flyway-commandline-3.2.1-windows-x64.zip',
    destination_directory => 'C:\Windows\Temp'
}

Solution

  • You can create a custom fact to provide that information (named something like modulename/lib/facter/module_temp_dir.rb):

    Facter.add('module_temp_dir') do
      setcode do
        if Puppet::Util::Platform.windows?
            require 'win32/registry'
    
            value = nil
            begin
              # looking at current user may likely fail because it's likely going to be LocalSystem
              hive = Win32::Registry::HKEY_CURRENT_USER
              hive.open('Environment', Win32::Registry::KEY_READ | 0x100) do |reg|
                value = reg['TEMP']
              end
            rescue Win32::Registry::Error => e
              value = nil
            end
    
            if value.nil?
              begin
                hive = Win32::Registry::HKEY_LOCAL_MACHINE
                hive.open('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', Win32::Registry::KEY_READ | 0x100) do |reg|
                  value = reg['TEMP']
                end
              rescue Win32::Registry::Error => e
                value = nil
              end
            end
          end
    
          value
        end
      end
    end
    

    This approach is preferred over simply using ENV['TEMP'] as it is not subject to being tampered with like environment variables could be at runtime.

    If you are not concerned with the value being tampered with and/or you may want to change it at runtime locally, you can instead do something like:

    Facter.add('module_temp_dir') do
      setcode do
       ENV['TEMP']       
      end
    end
    

    As a followup for providing some/all of the environment variables automatically as facts, I've filed https://tickets.puppetlabs.com/browse/FACT-1346. It possible we can quickly move forward on providing more of the important system provided environment variables where to provide all of them, we would need the whitelisting feature that is currently stated as blocking that ticket (https://tickets.puppetlabs.com/browse/FACT-718).

    Reference:

    https://github.com/chocolatey/puppet-chocolatey/blob/master/lib/facter/choco_install_path.rb and https://github.com/chocolatey/puppet-chocolatey/blob/master/lib/puppet_x/chocolatey/chocolatey_install.rb