Best Inspec_ruby code snippet using Inspec.cached
helpers.rb
Source:helpers.rb
...45 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 modules...
gcp_helpers.rb
Source:gcp_helpers.rb
...27 desc 'The GKE cache resource contains functions consumed by the CIS/PCI28 Google profiles:29 https://github.com/GoogleCloudPlatform/inspec-gcp-cis-benchmark'30 attr_reader :gke_locations31 @@cached_gke_clusters = []32 @@gke_clusters_cached = false33 def initialize(project: '', gke_locations: [])34 @gcp_project_id = project35 @gke_locations = if gke_locations.join.empty?36 all_gcp_locations37 else38 gke_locations39 end40 end41 def gke_clusters_cache42 set_gke_clusters_cache unless gke_cached?43 @@cached_gke_clusters44 end45 def gke_cached?46 @@gke_clusters_cached47 end48 def set_gke_clusters_cache49 @@cached_gke_clusters = []50 collect_gke_clusters_by_location(@gke_locations)51 @@gke_clusters_cached = true52 end53 private54 def collect_gke_clusters_by_location(gke_locations)55 gke_locations.each do |gke_location|56 inspec.google_container_clusters(project: @gcp_project_id,57 location: gke_location).cluster_names58 .each do |gke_cluster|59 @@cached_gke_clusters.push({ cluster_name: gke_cluster,60 location: gke_location })61 end62 end63 end64end65# Cache for GCE instances66#67class GCECache < GCPBaseCache68 name 'GCECache'69 desc 'The GCE cache resource contains functions consumed by the CIS/PCI70 Google profiles:71 https://github.com/GoogleCloudPlatform/inspec-gcp-cis-benchmark'72 attr_reader :gce_zones73 @@cached_gce_instances = []74 @@gce_instances_cached = false75 def initialize(project: '', gce_zones: [])76 @gcp_project_id = project77 @gce_zones = if gce_zones.join.empty?78 inspec.google_compute_zones(project: @gcp_project_id)79 .zone_names80 else81 gce_zones82 end83 end84 def gce_instances_cache85 set_gce_instances_cache unless gce_cached?86 @@cached_gce_instances87 end88 def gce_cached?89 @@gce_instances_cached90 end91 def set_gce_instances_cache92 @@cached_gce_instances = []93 # Loop/fetch/cache the names and locations of GKE clusters94 @gce_zones.each do |gce_zone|95 inspec.google_compute_instances(project: @gcp_project_id, zone: gce_zone)96 .instance_names.each do |instance|97 @@cached_gce_instances.push({ name: instance, zone: gce_zone })98 end99 end100 # Mark the cache as full101 @@gce_instances_cached = true102 @@cached_gce_instances103 end104end...
gcp_test.rb
Source:gcp_test.rb
...27 desc 'The GKE cache resource contains functions consumed by the CIS/PCI28 Google profiles:29 https://github.com/GoogleCloudPlatform/inspec-gcp-cis-benchmark'30 attr_reader :gke_locations31 @@cached_gke_clusters = []32 @@gke_clusters_cached = false33 def initialize(project: '', gke_locations: [])34 @gcp_project_id = project35 @gke_locations = if gke_locations.join.empty?36 all_gcp_locations37 else38 gke_locations39 end40 end41 def gke_clusters_cache42 set_gke_clusters_cache unless gke_cached?43 @@cached_gke_clusters44 end45 def gke_cached?46 @@gke_clusters_cached47 end48 def set_gke_clusters_cache49 @@cached_gke_clusters = []50 collect_gke_clusters_by_location(@gke_locations)51 @@gke_clusters_cached = true52 end53 private54 def collect_gke_clusters_by_location(gke_locations)55 gke_locations.each do |gke_location|56 inspec.google_container_clusters(project: @gcp_project_id,57 location: gke_location).cluster_names58 .each do |gke_cluster|59 @@cached_gke_clusters.push({ cluster_name: gke_cluster,60 location: gke_location })61 end62 end63 end64end65# Cache for GCE instances66#67class GCECache < GCPBaseCache68 name 'GCECache'69 desc 'The GCE cache resource contains functions consumed by the CIS/PCI70 Google profiles:71 https://github.com/GoogleCloudPlatform/inspec-gcp-cis-benchmark'72 attr_reader :gce_zones73 @@cached_gce_instances = []74 @@gce_instances_cached = false75 def initialize(project: '', gce_zones: [])76 @gcp_project_id = project77 @gce_zones = if gce_zones.join.empty?78 inspec.google_compute_zones(project: @gcp_project_id)79 .zone_names80 else81 gce_zones82 end83 end84 def gce_instances_cache85 set_gce_instances_cache unless gce_cached?86 @@cached_gce_instances87 end88 def gce_cached?89 @@gce_instances_cached90 end91 def set_gce_instances_cache92 @@cached_gce_instances = []93 # Loop/fetch/cache the names and locations of GKE clusters94 @gce_zones.each do |gce_zone|95 inspec.google_compute_instances(project: @gcp_project_id, zone: gce_zone)96 .instance_names.each do |instance|97 @@cached_gce_instances.push({ name: instance, zone: gce_zone })98 end99 end100 # Mark the cache as full101 @@gce_instances_cached = true102 @@cached_gce_instances103 end104end...
cached
Using AI Code Generation
1class Inspec::Resources::File < Inspec.resource(1)2 def initialize(path)3class Inspec::Resources::File < Inspec.resource(2)4 def initialize(path)5class Inspec::Resources::File < Inspec.resource(3)6 def initialize(path)7class Inspec::Resources::File < Inspec.resource(4)8 def initialize(path)9class Inspec::Resources::File < Inspec.resource(5)10 def initialize(path)11class Inspec::Resources::File < Inspec.resource(6)12 def initialize(path)13class Inspec::Resources::File < Inspec.resource(7)14 def initialize(path)
cached
Using AI Code Generation
1 class CachedMethod < Inspec.resource(1)2 its('foo') { should eq true }3 inspec.cached(:foo) do4 class CachedMethod2 < Inspec.resource(1)5 its('foo') { should eq true }6 CachedMethod.new(inspec).foo7 class CachedMethod3 < Inspec.resource(1)8 its('foo') { should eq true }9 class CachedMethod4 < Inspec.resource(1)10 its('foo') { should eq true }11 CachedMethod.instance_method(:foo).bind(self).call
cached
Using AI Code Generation
1def cached(name)2 define_method(name) do3 unless instance_variable_defined?(ivar)4 instance_variable_get(ivar)5def cached(name)6 define_method(name) do7 unless instance_variable_defined?(ivar)8 instance_variable_get(ivar)9def cached(name)10 define_method(name) do11 unless instance_variable_defined?(ivar)12 instance_variable_get(ivar)13def cached(name)14 define_method(name) do15 unless instance_variable_defined?(ivar)16 instance_variable_get(ivar)
cached
Using AI Code Generation
1class Inspec::Resources::File < Inspec.resource(1)2 def initialize(path)3class Inspec::Resources::File < Inspec.resource(2)4 def initialize(path)5class Inspec::Resources::File < Inspec.resource(3)6 def initialize(path)7class Inspec::Resources::File < Inspec.resource(4)8 def initialize(path)9class Inspec::Resources::File < Inspec.resource(5)10 def initialize(path)11class Inspec::Resources::File < Inspec.resource(6)12 def initialize(path)13class Inspec::Resources::File < Inspec.resource(7)14 def initialize(path)
cached
Using AI Code Generation
1 class CachedMethod < Inspec.resource(1)2 its('foo') { should eq true }3 inspec.cached(:foo) do4 class CachedMethod2 < Inspec.resource(1)5 its('foo') { should eq true }6 CachedMethod.new(inspec).foo7 class CachedMethod3 < Inspec.resource(1)8 its('foo') { should eq true }9 class CachedMethod4 < Inspec.resource(1)10 its('foo') { should eq true }11 CachedMethod.instance_method(:foo).bind(self).call
cached
Using AI Code Generation
1def cached(name)2 define_method(name) do3 unless instance_variable_defined?(ivar)4 instance_variable_get(ivar)5def cached(name)6 define_method(name) do7 unless instance_variable_defined?(ivar)8 instance_variable_get(ivar)9def cached(name)10 define_method(name) do11 unless instance_variable_defined?(ivar)12 instance_variable_get(ivar)13def cached(name)14 define_method(name) do15 unless instance_variable_defined?(ivar)16 instance_variable_get(ivar)
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!!