Merge pull request #245 from chef/schisamo/os_env-windows

Add Windows support to the `os_env` resource
This commit is contained in:
Christoph Hartmann 2015-11-19 16:09:35 +01:00
commit d897cf22a7
4 changed files with 29 additions and 9 deletions

View file

@ -20,13 +20,16 @@ class OsEnv < Inspec.resource(1)
def initialize(env = nil)
@osenv = env
@content = nil
@content = params[env] unless env.nil?
@content = value_for(env) unless env.nil?
end
def split
# we can't take advantage of `File::PATH_SEPARATOR` as code is
# evaluated on the host machine
path_separator = inspec.os.windows? ? ';' : ':'
# -1 is required to catch cases like dir1::dir2:
# where we have a trailing :
@content.nil? ? [] : @content.split(':', -1)
@content.nil? ? [] : @content.split(path_separator, -1)
end
def to_s
@ -39,15 +42,25 @@ class OsEnv < Inspec.resource(1)
private
def params
return @params if defined? @params
out = inspec.command('env')
out = inspec.command('printenv') unless out.exit_status == 0
def value_for(env)
command = if inspec.os.windows?
"$Env:#{env}"
else
'env'
end
out = inspec.command(command)
unless out.exit_status == 0
skip_resource "Can't read environment variables on #{os[:family]}. "\
"Tried `env` and `printenv` which returned #{out.exit_status}"
"Tried `#{command}` which returned #{out.exit_status}"
end
@params = SimpleConfig.new(out.stdout).params
if inspec.os.windows?
out.stdout.strip
else
params = SimpleConfig.new(out.stdout).params
params[env]
end
end
end

View file

@ -109,6 +109,7 @@ class MockLoader
'secedit /export /cfg win_secpol.cfg' => cmd.call('success'),
'del win_secpol.cfg' => cmd.call('success'),
'env' => cmd.call('env'),
'$Env:PATH' => cmd.call('$env-PATH'),
# registry key test
'2790db1e88204a073ed7fd3493f5445e5ce531afd0d2724a0e36c17110c535e6' => cmd.call('reg_schedule'),
'Auditpol /get /subcategory:\'User Account Management\' /r' => cmd.call('auditpol'),

View file

@ -0,0 +1 @@
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\opscode\chef\bin\

View file

@ -6,8 +6,13 @@ require 'helper'
require 'inspec/resource'
describe 'Inspec::Resources::OsEnv' do
it 'verify ntp config parsing' do
it 'verify env parsing' do
resource = load_resource('os_env', 'PATH')
_(resource.split).must_equal %w{/usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin}
end
it 'read env variable on Windows' do
resource = MockLoader.new(:windows).load_resource('os_env', 'PATH')
_(resource.split).must_equal ['C:\Windows\system32', 'C:\Windows', 'C:\Windows\System32\Wbem', 'C:\Windows\System32\WindowsPowerShell\v1.0\\', 'C:\opscode\chef\bin\\']
end
end