使用 Puppet 在 Windows 上获取临时目录

Get Temp Directory on Windows using Puppet

我正在尝试使用 download_file 模块下载文件并想将其保存到临时目录。是否有一种内置的方法可以使用 Puppet 执行此操作而无需将其硬编码为 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'
}

您可以创建一个自定义事实来提供该信息(名称类似于 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

这种方法优于简单地使用 ENV['TEMP'],因为它不会像运行时的​​环境变量那样被篡改。

如果您不担心被篡改的值 and/or 您可能希望在本地运行时更改它,您可以改为执行以下操作:

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

作为自动提供 some/all 个环境变量作为事实的后续行动,我已提交 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)。

参考:

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