Best Inspec_ruby code snippet using Inspec.run
helpers.rb
Source:helpers.rb
...14# limitations under the License.15#16# Author: Peter Mudd (https://github.com/muddman)17# C:\salt\salt-call.bat --config-dir=C:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt state.show_highstate18# --out yaml |Select-String -Pattern "__sls__", "__env__", "- run", "- order:" -NotMatch19# GENERAL HELPERS20require 'inspec/resources/registry_key'21def server?22 if defined?(@cache_server)23 Inspec::Log.debug('(server?) using cache @cache_server')24 return @cache_server25 end26 begin27 @cache_server = inspec.registry_key('HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion')['ProductName'].match? 'Server'28 rescue StandardError => e29 Inspec::Log.error('(server?) rescue:' + e.message)30 return false31 end32 Inspec::Log.debug('(server?) ending')33 @cache_server34end35# SALTSTACK HELPERS36require 'safe_yaml'37require 'train'38require 'timeout'39require "inspec/log"40require 'json'41require 'os'42SafeYAML::OPTIONS[:default_mode] = :safe43# https://www.inspec.io/docs/reference/inputs/44def set_input_pillar_default45 input('pillar', value: get_pillar_default, type: 'hash', description: 'SaltStack Pillar Data')46end47def get_pillar48 if defined?(@cache_pillar)49 Inspec::Log.debug('(get_pillar?) returning cached value')50 return @cache_pillar51 end52 @cache_pillar = try_get_pillar53 if defined?(@cache_pillar)54 Inspec::Log.debug('(get_pillar) success, got pillar. Cached result.')55 @cache_pillar56 end57end58def try_get_pillar59 # require 'pp'; pp input('pillar').diagnostic_string;60 # REMOVE THIS61 # return get_pillar_from_inspec_pillar_file62 unless input('pillar').is_a?(Inspec::Input::NO_VALUE_SET)63 Inspec::Log.debug('Got pillar from kitchen input.')64 puts 'INFO: Got pillar from kitchen input.'65 return input('pillar')66 end67 # pillar_from_minion = get_pillar_from_minion68 pillar_from_minion = ingest_from_minion('yaml', 'c:\salt\salt-call.bat --config-dir=C:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt pillar.items --retcode-passthrough | Select-String -Pattern "----------" -NotMatch')69 unless !defined?(pillar_from_minion) || pillar_from_minion == []70 Inspec::Log.debug('Got pillar from the target minion using WinRM.')71 puts 'INFO: Got pillar from the target minion using WinRM.'72 return pillar_from_minion['local']73 end74 pillar_from_inspec_pillar_file = get_pillar_from_inspec_pillar_file75 unless !defined?(pillar_from_inspec_pillar_file) || pillar_from_inspec_pillar_file == []76 Inspec::Log.debug('Got pillar from the inspec pillar file.')77 puts 'INFO: Got pillar from the inspec pillar file.'78 return pillar_from_inspec_pillar_file79 end80 raise 'Unable to get pillar from input, minion or local inspec pillar file.'81end82def get_pillar_from_inspec_pillar_file83 if defined?(@cache_pillar_from_inspec_pillar_file)84 Inspec::Log.debug('[get_pillar_from_inspec_pillar_file] returning cached value')85 return @cache_pillar_from_inspec_pillar_file86 end87 pillar_file = ENV['INSPEC_TEST_SALT_PILLAR'] || 'pillar.example'88 begin89 @cache_pillar_from_inspec_pillar_file = YAML.safe_load(File.read(pillar_file)) if File.exist?(pillar_file)90 rescue StandardError => e91 Inspec::Log.warn('[get_pillar_from_inspec_pillar_file] ' + e.message)92 return []93 end94 if defined?(@cache_pillar_from_inspec_pillar_file)95 Inspec::Log.debug('[get_pillar_from_inspec_pillar_file] success, got the pillar from the inspec file. Cached result.')96 @cache_pillar_from_inspec_pillar_file97 end98end99def ingest_from_minion(type, ps_cmd, max_retries = 20, sec_timeout = 10)100 # grep "WinRM address:" $(ls -t .kitchen/logs/*.log | head -n2 | tail -n1) | sed 's/^.*: //'101 # Test port open: nc -z -w1 localhost 55985;echo $?102 # nc -z -w1 $(sed -n -e 's/^.*WinRM address: //p' $(ls -t .kitchen/logs/*.log | sed -n '2p') | cut -f1 -d:) $(sed -n -e 's/^.*WinRM address: //p' $(ls -t .kitchen/logs/*.log | sed -n '2p') | cut -f2 -d:); echo $? 103 # cd .kitchen/kitchen-vagrant/{instance name}; vagrant winrm --command whoami104 # cd .kitchen/kitchen-vagrant/{instance name}; vagrant winrm-config105 # cmd ="nc -z -w1 $(sed -n -e 's/^.*WinRM address: //p' $(ls -t .kitchen/logs/*.log | sed -n '2p') | cut -f1 -d:) $(sed -n -e 's/^.*WinRM address: //p' $(ls -t .kitchen/logs/*.log | sed -n '2p') | cut -f2 -d:); echo $?"106 retries ||= 0107 Inspec::Log.debug("Ingesting #{type} content using `#{ps_cmd}` with timout of #{sec_timeout} and a max of #{max_retries} retries.")108 # require 'pry'; binding.pry109 begin110 # https://www.rubydoc.info/gems/train/0.14.1/Train%2FTransports%2FLocal%2FConnection:run_command111 # Train.Plugins.Transport.Connection train.connection.run_command112 Timeout.timeout(sec_timeout) do113 @my_result = JSON.parse(backend::backend.run_command(ps_cmd).stdout) if type == 'json'114 @my_result =YAML.safe_load(backend::backend.run_command(ps_cmd).stdout) if type == 'yaml'115 end116 rescue => e117 Inspec::Log.debug("`#{e.message}`, target may be rebooting after highstate. Remaining retries: #{max_retries - retries}")118 puts("`#{e.message}`, target may be rebooting after highstate. Remaining retries: #{max_retries - retries}")119 if (retries += 1) < max_retries120 retry121 else122 begin123 backend::backend.run_command('whoami').stdout124 rescue => e125 msg = "Unable to get whoami from backend::backend.run_command: #{e.message}"126 puts(msg)127 Inspec::Log.debug(msg)128 end129 if OS.windows?130 pwsh_cmd = '$test_path=".kitchen/kitchen-vagrant/$(Get-ChildItem -Path .kitchen/logs/*.log | Where-Object {$_.Name -ne "kitchen.log"} | Sort-Object -Property @{Expression = {$_.LastWriteTime}; Descending = $True} | Select-Object -Property BaseName -First 1 -expandproperty BaseName)"; Set-Location -Path $test_path; $test_vagrantfile = "$test_path/Vagrantfile"; Set-Content -Path $test_vagrantfile -Value (get-content -Path $test_vagrantfile | Select-String -Pattern "vagrant_vb_guest.rb" -NotMatch); Set-Location -Path $test_path; vagrant winrm'131 cmd = "powershell -command '#{pwsh_cmd}'"132 else133 cmd = "cd .kitchen/kitchen-vagrant/$(ls -t .kitchen/logs/*.log | grep -v .kitchen/logs/kitchen.log | head -n1 | cut -f3 -d/ | awk -F. '{print $1}'); vagrant winrm"134 end135 if system( cmd )136 puts('Successfully connected via `vagrant winrm`')137 Inspec::Log.debug('Successfully connected via `vagrant winrm`')138 else139 msg = 'Failed to connect via `vagrant winrm`'140 puts(msg)141 Inspec::Log.debug(msg)142 # abort msg143 end144 end145 end146 if defined?(@my_result)147 Inspec::Log.debug("Ingested #{type} content successfully from minion using Train.Plugins.Transport.Connection.")148 @my_result149 else150 Inspec::Log.debug('Failed to get content from minion using Train.Plugins.Transport.Connection.')151 puts "WARNING: Failed to get content from minion using Train.Plugins.Transport.Connection."152 []153 end154end155# pp get_mystates_from_highstate('module','chocolatey','bootstrap')156# pp get_mystates_from_highstate('module','user','current')157# pp get_mystates_from_highstate('state','system','hostname')158def get_highstate_from_minion159 if defined?(@cache_highstate_from_minion)160 Inspec::Log.debug('Returning cached @cache_highstate_from_minion.')161 return @cache_highstate_from_minion162 end163 # ingest_from_minion('yaml', 'C:\salt\salt-call.bat --config-dir=C:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt state.show_highstate --out yaml |Select-String -Pattern "__sls__", "__env__", "- run", "- order:" -NotMatch')164 highstate_from_minion = ingest_from_minion('json', 'C:\salt\salt-call.bat --config-dir=C:\Users\vagrant\AppData\Local\Temp\kitchen\etc\salt state.show_highstate --out json')165 if highstate_from_minion != []166 Inspec::Log.debug('Saving highstate to cache @cache_highstate_from_minion.')167 @cache_highstate_from_minion = highstate_from_minion['local']168 @cache_highstate_from_minion169 else170 Inspec::Log.error('Failed to get highstate.')171 abort 'Failed to get highstate.'172 end173end174# Example modules175# "windows.module.status.uptime"=>176# {"module"=>177# [{"status.uptime"=>[{"human_readable"=>true}]},178# {"require"=>["windows.module.user.current"]},179# "run",180# {"order"=>10004}],181# "__sls__"=>"windows.modules",182# "__env__"=>"base"},183# "chocolatey.bootstrap"=>184# {"module"=>185# [{"chocolatey.bootstrap"=>nil},186# {"unless"=>"where.exe chocolatey"},187# "run",188# {"order"=>10010}],189# "__sls__"=>"windows.system.packages.chocolatey.bootstrap",190# "__env__"=>"base"},191# Example State192# {"windows.state.system.computer_desc.description"=>193# {"system"=>194# [{"name"=>"Saltstack Computer Description"},195# {"require"=>["windows.state.system.hostname.saltstack1"]},196# "computer_desc",197# {"order"=>10000}],198# "__sls__"=>"windows.states",199# "__env__"=>"base"},200def get_mystates_from_highstate(type, find_state, find_function)201 found_states = {}...
01_simp_profile_inspec_spec.rb
Source:01_simp_profile_inspec_spec.rb
1require 'spec_helper_acceptance'2require 'json'3test_name 'Check Inspec for simp profile'4describe 'run inspec against the appropriate fixtures' do5 profiles_to_validate = ['disa_stig']6 hosts.each do |host|7 profiles_to_validate.each do |profile|8 context "for profile #{profile}" do9 context "on #{host}" do10 profile_path = File.join(11 fixtures_path,12 'inspec_profiles',13 "#{fact_on(host, 'operatingsystem')}-#{fact_on(host, 'operatingsystemmajrelease')}-#{profile}"14 )15 unless File.exist?(profile_path)16 it 'should run inspec' do17 skip("No matching profile available at #{profile_path}")18 end19 else20 before(:all) do21 @inspec = Simp::BeakerHelpers::Inspec.new(host, profile)22 @inspec_report = {:data => nil}23 end24 it 'should run inspec' do25 @inspec.run26 end27 it 'should have an inspec report' do28 @inspec_report[:data] = @inspec.process_inspec_results29 info = [30 'Results:',31 " * Passed: #{@inspec_report[:data][:passed]}",32 " * Failed: #{@inspec_report[:data][:failed]}",33 " * Skipped: #{@inspec_report[:data][:skipped]}"34 ]35 puts info.join("\n")36 @inspec.write_report(@inspec_report[:data])37 end38 it 'should have run some tests' do39 expect(@inspec_report[:data][:failed] + @inspec_report[:data][:passed]).to be > 040 end41 it 'should not have any failing tests' do42 if @inspec_report[:data][:failed] > 043 puts @inspec_report[:data][:report]44 end45 expect( @inspec_report[:data][:failed] ).to eq(0)46 end47 end48 end49 end50 end51 end52end...
run
Using AI Code Generation
1Inspec::Runner.new('1.rb').run2Inspec::Runner.new('2.rb').run3Inspec::Runner.new('3.rb').run4Inspec::Runner.new('4.rb').run5Inspec::Runner.new('5.rb').run6Inspec::Runner.new('6.rb').run7Inspec::Runner.new('7.rb').run8Inspec::Runner.new('8.rb').run9Inspec::Runner.new('9.rb').run10Inspec::Runner.new('10.rb').run11Inspec::Runner.new('11.rb').run12Inspec::Runner.new('12.rb').run13Inspec::Runner.new('13.rb').run14Inspec::Runner.new('14.rb').run15Inspec::Runner.new('15.rb').run
run
Using AI Code Generation
1Inspec::Runner.new(File.join(Dir.pwd, '1.rb')).run2Inspec::Runner.new(File.join(Dir.pwd, '2.rb')).run3Inspec::Runner.new(File.join(Dir.pwd, '3.rb')).run4Inspec::Runner.new(File.join(Dir.pwd, '4.rb')).run5Inspec::Runner.new(File.join(Dir.pwd, '5.rb')).run6Inspec::Runner.new(File.join(Dir.pwd, '6.rb')).run7Inspec::Runner.new(File.join(Dir.pwd, '7.rb')).run8Inspec::Runner.new(File.join(Dir.pwd, '8.rb')).run9Inspec::Runner.new(File.join(Dir.pwd, '9.rb')).run10Inspec::Runner.new(File.join(Dir.pwd, '10.rb')).run11Inspec::Runner.new(File.join(Dir.pwd, '11.rb')).run12Inspec::Runner.new(File.join(Dir.pwd, '12.rb')).run
run
Using AI Code Generation
1Inspec::Runner.new.run('profile_path')2Inspec::Runner.new.run('profile_path')3C. inspec.profile.my_profile('my_attribute')4D. inspec.profile.my_profile.my_attribute('my_attribute')5inspec.profile.my_profile('my_attribute')
run
Using AI Code Generation
1 expect(true).to eq(true)2 expect(true).to eq(true)3 expect(true).to eq(true)4 expect(true).to eq(true)5 expect(true).to eq(true)6 expect(true).to eq(true)7 expect(true).to eq(true)8 expect(true).to eq(true)9 expect(true).to eq(true)10 expect(true).to eq(true)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!