Best Inspec_ruby code snippet using Inspec.load
inspec.rb
Source:inspec.rb
...36 # (https://github.com/rspec/rspec-core/issues/1254)37 # Tell test kitchen not to multithread the verify step38 no_parallel_for :verify39 default_config :inspec_tests, []40 default_config :load_plugins, true41 default_config :plugin_config, {}42 default_config :backend_cache, true43 # A lifecycle method that should be invoked when the object is about44 # ready to be used. A reference to an Instance is required as45 # configuration dependant data may be access through an Instance. This46 # also acts as a hook point where the object may wish to perform other47 # last minute checks, validations, or configuration expansions.48 #49 # @param instance [Instance] an associated instance50 # @return [self] itself, for use in chaining51 # @raise [ClientError] if instance parameter is nil52 def finalize_config!(instance)53 super54 # We want to switch kitchen-inspec to look for its tests in55 # `cookbook_dir/test/recipes` instead of `cookbook_dir/test/integration`56 # Unfortunately there is no way to read `test_base_path` from the57 # .kitchen.yml, it can only be provided on the CLI.58 # See https://github.com/test-kitchen/test-kitchen/issues/107759 inspec_test_dir = File.join(config[:kitchen_root], "test", "recipes")60 if File.directory?(inspec_test_dir)61 config[:test_base_path] = inspec_test_dir62 end63 self64 end65 # (see Base#call)66 def call(state)67 logger.debug("Initialize InSpec")68 # gather connection options69 opts = runner_options(instance.transport, state, instance.platform.name, instance.suite.name)70 logger.debug "Options #{opts.inspect}"71 # add inputs and waivers72 setup_inputs(opts, config)73 setup_waivers(opts, config)74 # setup Inspec75 ::Inspec::Log.init(STDERR)76 ::Inspec::Log.level = Kitchen::Util.from_logger_level(logger.level)77 load_plugins # Must load plugins prior to config validation78 inspec_config = ::Inspec::Config.new(opts)79 # handle plugins80 setup_plugin_config(inspec_config)81 # initialize runner82 runner = ::Inspec::Runner.new(inspec_config)83 # add each profile to runner84 tests = collect_tests85 profile_ctx = nil86 tests.each do |target|87 profile_ctx = runner.add_target(target)88 end89 profile_ctx ||= []90 profile_ctx.each do |profile|91 logger.info("Loaded #{profile.name} ")92 end93 exit_code = runner.run94 # 101 is a success as well (exit with no fails but has skipped controls)95 return if exit_code == 0 || exit_code == 10196 raise ActionFailed, "InSpec Runner returns #{exit_code}"97 end98 private99 def setup_waivers(opts, config)100 # InSpec expects the singular inflection101 opts[:waiver_file] = config[:waiver_files] || []102 end103 def setup_inputs(opts, config)104 inspec_version = Gem::Version.new(::Inspec::VERSION)105 # Handle input files106 if config[:attrs]107 logger.warn("kitchen-inspec: please use 'input-files' instead of 'attrs'")108 config[:input_files] = config[:attrs]109 end110 if config[:input_files]111 # Note that inspec expects the singular inflection, input_file112 files_key = inspec_version >= Gem::Version.new("3.10") ? :input_file : :attrs113 opts[files_key] = config[:input_files]114 end115 # Handle YAML => Hash inputs116 if config[:attributes]117 logger.warn("kitchen-inspec: please use 'inputs' instead of 'attributes'")118 config[:inputs] = config[:attributes]119 end120 if config[:inputs]121 # Version here is dependent on https://github.com/inspec/inspec/issues/3856122 inputs_key = inspec_version >= Gem::Version.new("4.10") ? :inputs : :attributes123 opts[inputs_key] = Hashie.stringify_keys config[:inputs]124 end125 end126 def load_plugins127 return unless config[:load_plugins]128 v2_loader = ::Inspec::Plugin::V2::Loader.new129 v2_loader.load_all130 v2_loader.exit_on_load_error131 # Suppress input caching or all suites will get identical inputs, not different ones132 if ::Inspec::InputRegistry.instance.respond_to?(:cache_inputs=) && config[:cache_inputs]133 ::Inspec::InputRegistry.instance.cache_inputs = !!config[:cache_inputs]134 end135 end136 def setup_plugin_config(inspec_config)137 return unless config[:load_plugins]138 unless inspec_config.respond_to?(:merge_plugin_config)139 logger.warn("kitchen-inspec: skipping `plugin_config` which requires InSpec version 4.26.2 or higher. Your version: #{::Inspec::VERSION}")140 return141 end142 config[:plugin_config].each do |plugin_name, plugin_config|143 inspec_config.merge_plugin_config(plugin_name, plugin_config)144 end145 end146 # (see Base#load_needed_dependencies!)147 def load_needed_dependencies!148 require "inspec"149 # TODO: this should be easier. I would expect to load a single class here150 # load supermarket plugin, this is part of the inspec gem151 require "bundles/inspec-supermarket/api"152 require "bundles/inspec-supermarket/target"153 # load the compliance plugin154 require "bundles/inspec-compliance/configuration"155 require "bundles/inspec-compliance/support"156 require "bundles/inspec-compliance/http"157 require "bundles/inspec-compliance/api"158 require "bundles/inspec-compliance/target"159 end160 # Returns an Array of test suite filenames for the related suite currently161 # residing on the local workstation. Any special provisioner-specific162 # directories (such as a Chef roles/ directory) are excluded.163 #164 # we support the base directories165 # - test/integration166 # - test/integration/inspec (preferred if used with other test environments)167 #...
audit_report.rb
Source:audit_report.rb
...41 fetcher = node['audit']['fetcher']42 attributes = node.run_state['audit_attributes'].to_h43 # add chef node data as an attribute if enabled44 attributes['chef_node'] = chef_node_attribute_data if node['audit']['chef_node_attribute_enabled']45 # load inspec, supermarket bundle and compliance bundle46 load_needed_dependencies47 # confirm our inspec version is valid48 validate_inspec_version49 # detect if we run in a chef client with chef server50 load_chef_fetcher if reporters.include?('chef-server') ||51 reporters.include?('chef-server-automate') ||52 %w(chef-server chef-server-automate).include?(fetcher)53 load_automate_fetcher if fetcher == 'chef-automate'54 # true if profile is due to run (see libraries/helper.rb)55 if check_interval_settings(interval, interval_enabled, interval_time)56 # create a file with a timestamp to calculate interval timing57 create_timestamp_file if interval_enabled58 reporter_format = 'json'59 if Gem::Version.new(::Inspec::VERSION) >= Gem::Version.new(MIN_INSPEC_VERSION_AUTOMATE_REPORTER)60 reporter_format = 'json-automate'61 end62 # return hash of opts to be used by runner63 opts = get_opts(reporter_format, quiet, attributes)64 # instantiate inspec runner with given options and run profiles; return report65 report = call(opts, profiles)66 # send report to the correct reporter (automate, chef-server)67 if !report.empty?68 # iterate through reporters69 reporters.each do |reporter|70 send_report(reporter, server, profiles, report)71 end72 else73 Chef::Log.error 'Audit report was not generated properly, skipped reporting'74 end75 else76 Chef::Log.info 'Audit run skipped due to interval configuration'77 end78 end79 # overwrite the default run_report_safely to be able to throw exceptions80 def run_report_safely(run_status)81 run_report_unsafe(run_status)82 rescue Exception => e # rubocop:disable Lint/RescueException83 Chef::Log.error("Report handler #{self.class.name} raised #{e.inspect}")84 Array(e.backtrace).each { |line| Chef::Log.error(line) }85 # force a chef-client exception if user requested it86 throw e if e.is_a?(Reporter::AuditEnforcer::ControlFailure) || node['audit']['fail_if_not_present']87 ensure88 @run_status = nil89 end90 def validate_inspec_version91 minimum_ver_msg = "This audit cookbook version requires InSpec #{MIN_INSPEC_VERSION} or newer, aborting compliance scan..."92 raise minimum_ver_msg if Gem::Version.new(::Inspec::VERSION) < Gem::Version.new(MIN_INSPEC_VERSION)93 # check if we have a valid version for backend caching94 backend_cache_msg = 'inspec_backend_cache requires InSpec version >= 1.47.0'95 Chef::Log.warn backend_cache_msg if node['audit']['inspec_backend_cache'] &&96 (Gem::Version.new(::Inspec::VERSION) < Gem::Version.new('1.47.0'))97 end98 def load_needed_dependencies99 require 'inspec'100 # load supermarket plugin, this is part of the inspec gem101 require 'bundles/inspec-supermarket/api'102 require 'bundles/inspec-supermarket/target'103 # load the compliance plugin104 require 'bundles/inspec-compliance/configuration'105 require 'bundles/inspec-compliance/support'106 require 'bundles/inspec-compliance/http'107 require 'bundles/inspec-compliance/api'108 require 'bundles/inspec-compliance/target'109 end110 # we expect inspec to be loaded before111 def load_chef_fetcher112 Chef::Log.debug "Load Chef Server fetcher from: #{cookbook_vendor_path}"113 $LOAD_PATH.unshift(cookbook_vendor_path)114 require 'chef-server/fetcher'115 end116 def load_automate_fetcher117 Chef::Log.debug "Load Chef Automate fetcher from: #{cookbook_vendor_path}"118 $LOAD_PATH.unshift(cookbook_vendor_path)119 require 'chef-automate/fetcher'120 end121 def get_opts(reporter, quiet, attributes)122 output = quiet ? ::File::NULL : $stdout123 Chef::Log.debug "Reporter is [#{reporter}]"124 # You can pass nil (no waiver files), one file, or an array. InSpec expects an Array regardless.125 waivers = Array(node['audit']['waiver_file']).to_a126 waivers.delete_if do |file|127 unless File.exist?(file)128 Chef::Log.error "The specified InSpec waiver file #{file} is missing, skipping it..."129 true130 end...
Rakefile
Source:Rakefile
...24 pp profile.check25 end26end27task :changelog do28 # Automatically generate a changelog for this project. Only loaded if29 # the necessary gem is installed. By default its picking up the version from30 # inspec.yml. You can override that behavior with `rake changelog to=1.2.0`31 require 'yaml'32 metadata = YAML.load_file('inspec.yml')33 v = ENV['to'] || metadata['version']34 puts " * Generating changelog for version #{v}"35 require 'github_changelog_generator/task'36 GitHubChangelogGenerator::RakeTask.new :changelog do |config|37 config.future_release = v38 config.user = 'dev-sec'39 config.project = 'windows-patch-baseline'40 end41 Rake::Task[:changelog].execute42rescue LoadError43 puts '>>>>> GitHub Changelog Generator not loaded, omitting tasks'44end...
load
Using AI Code Generation
1inspec.load_resource('file', '/etc/passwd')2describe file('/etc/passwd') do3 it { should exist }
load
Using AI Code Generation
1describe file('c:/temp/test.txt') do2 it { should exist }3describe file('c:/temp/test.txt') do4 it { should be_file }5describe file('c:/temp/test.txt') do6 it { should be_readable }7describe file('c:/temp/test.txt') do8 it { should be_writable }9describe file('c:/temp/test.txt') do10 it { should be_executable }11describe file('c:/temp/test.txt') do12 it { should be_owned_by 'vagrant' }13describe file('c:/temp/test.txt') do14 it { should be_grouped_into 'vagrant' }15describe file('c:/temp/test.txt') do16 its('size') { should cmp 13 }17describe file('c:/temp/test.txt') do18 its('content') { should match /Hello World/ }19describe file('c:/temp/test.txt') do20 its('content') { should_not match /Hello World/ }21describe file('c:/temp/test.txt') do22 its('content') { should eq "Hello World\n" }23describe file('c:/temp/test.txt') do24 its('content') { should_not eq "Hello World\n" }25describe file('c:/temp/test.txt') do26 its('md5sum') { should eq '0f5e3d3e3c5c1e0f5d5d5d5d5c5c5c5c' }27describe file('c:/temp/test.txt') do28 its('sha256sum') { should eq '7a9c9d1b68a8b8e7a7c9e7e7b7d9b9b9b9c9d9b9d7e7c9e7c7a9c9d1b68a8b8e' }29describe file('c:/temp/test.txt') do30 its('sha1sum') { should eq '1f8ac10f23c5b5bc1167bda84b833e5c
load
Using AI Code Generation
1inspec('ls -ltrh')2inspec('ls -ltrh')3inspec('ls -ltrh')4inspec('ls -ltrh')5inspec('ls -ltrh')6inspec('ls -ltrh')7inspec('ls -ltrh')8inspec('ls -ltrh')9inspec('ls -ltrh')10inspec('ls -ltrh')11inspec('ls -ltrh')
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!!