'Library functions in Inspec Test
Team --
I have a ruby library helper in which I have defined multiple functions/methods. How do I reference those in Chef Inspec tests?
def interface_name
# some code with logic
end
In my specific use case, I am checking to see if a custom networking device was specified as a JSON parameter, and if it was, I am validating it make sure its real (incase they misspelled it) and also gathering its IP and state and other data as reported by Ohai
This is what I have so far, but I'm not sure if this is correct
describe file('/path/to/custom_attributes.json') do
it { should exist }
unless json('/path/to/custom_attributes.json').empty? do
its(['networking']['interface_name']) { should_not be_empty }
interface_name = file(json('/path/to/custom_attributes.json').params['networking']['interface_name'])
end
end
describe file('/etc/NetworkManager/system-connections/wired_connection') do
unless interface_name.empty?
its('content') { should_not match(/^interface-name=wl.*/mx) }
end
its('content') { should match(%r{ca-cert=/etc/ssl/certs/ca-certificates\.crt}mx) }
its('content') { should match(/id=\.corp.*type=ethernet.*autoconnect-priority=100.*dns-search=corp\.domain.com.*/mx) }
end
end
The problem / question is that if I gather the parameter directly from the JSON file, then I am bypassing all the validation logic that I'm doing in the library, which defeats the purpose. So, how do I get access to that library function/method in the Inspec test?
For reference, here is the function:
def interface_name
file = '/path/to/custom_attributes.json'
if File.exist?(file) && !File.stat(file).zero?
attributes = JSON.parse(File.read(file))
device_name = attributes['networking']['interface_name']
if device_name && !device_name.empty? && networking_devices.include?(device_name)
interface = device_name
Chef::Log.info("Valid custom interface provided, using \"#{device_name}\".")
else
Chef::Log.debug("Invalid interface (\"#{device_name}\") provided. Valid options are: \"#{networking_devices.keys}\"")
interface = nil
end
else
Chef::Log.debug('No custom interface provided.')
end
interface
rescue JSON::ParserError
nil
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
