Best Inspec_ruby code snippet using Inspec.fetcher
audit_report.rb
Source:audit_report.rb  
...23        interval_enabled = node['audit']['interval']['enabled']24        interval_time = node['audit']['interval']['time']25        profiles = node['audit']['profiles']26        quiet = node['audit']['quiet']27        fetcher = node['audit']['fetcher']28        attributes = node['audit']['attributes'].to_h29        # add chef node data as an attribute if enabled30        attributes['chef_node'] = chef_node_attribute_data if node['audit']['chef_node_attribute_enabled']31        # load inspec, supermarket bundle and compliance bundle32        load_needed_dependencies33        # confirm our inspec version is valid34        validate_inspec_version35        # detect if we run in a chef client with chef server36        load_chef_fetcher if reporters.include?('chef-server') ||37                             reporters.include?('chef-server-compliance') ||38                             reporters.include?('chef-server-visibility') ||39                             reporters.include?('chef-server-automate') ||40                             %w{chef-server chef-server-compliance chef-server-visibility chef-server-automate}.include?(fetcher)41        load_automate_fetcher if fetcher == 'chef-automate'42        # ensure authentication for Chef Compliance is in place, see libraries/compliance.rb43        login_to_compliance(server, user, token, refresh_token) if reporters.include?('chef-compliance')44        # true if profile is due to run (see libraries/helper.rb)45        if check_interval_settings(interval, interval_enabled, interval_time)46          # create a file with a timestamp to calculate interval timing47          create_timestamp_file if interval_enabled48          # return hash of opts to be used by runner49          opts = get_opts('json', quiet, attributes)50          # instantiate inspec runner with given options and run profiles; return report51          report = call(opts, profiles)52          # send report to the correct reporter (automate, compliance, chef-server)53          if !report.empty?54            # iterate through reporters55            reporters.each do |reporter|56              send_report(reporter, server, user, profiles, report)57            end58          else59            Chef::Log.error 'Audit report was not generated properly, skipped reporting'60          end61        else62          Chef::Log.info 'Audit run skipped due to interval configuration'63        end64      end65      # overwrite the default run_report_safely to be able to throw exceptions66      def run_report_safely(run_status)67        run_report_unsafe(run_status)68      rescue Exception => e # rubocop:disable Lint/RescueException69        Chef::Log.error("Report handler #{self.class.name} raised #{e.inspect}")70        Array(e.backtrace).each { |line| Chef::Log.error(line) }71        # force a chef-client exception if user requested it72        throw e if node['audit']['fail_if_not_present']73      ensure74        @run_status = nil75      end76      def validate_inspec_version77        minimum_ver_msg = "This audit cookbook version requires InSpec #{MIN_INSPEC_VERSION} or newer, aborting compliance scan..."78        raise minimum_ver_msg if Gem::Version.new(::Inspec::VERSION) < Gem::Version.new(MIN_INSPEC_VERSION)79        # check if we have a valid version for backend caching80        backend_cache_msg = 'inspec_backend_cache requires InSpec version >= 1.47.0'81        Chef::Log.warn backend_cache_msg if node['audit']['inspec_backend_cache'] &&82                                            (Gem::Version.new(::Inspec::VERSION) < Gem::Version.new('1.47.0'))83      end84      def load_needed_dependencies85        require 'inspec'86        # load supermarket plugin, this is part of the inspec gem87        require 'bundles/inspec-supermarket/api'88        require 'bundles/inspec-supermarket/target'89        # load the compliance plugin90        require 'bundles/inspec-compliance/configuration'91        require 'bundles/inspec-compliance/support'92        require 'bundles/inspec-compliance/http'93        require 'bundles/inspec-compliance/api'94        require 'bundles/inspec-compliance/target'95      end96      # we expect inspec to be loaded before97      def load_chef_fetcher98        Chef::Log.debug "Load Chef Server fetcher from: #{cookbook_vendor_path}"99        $LOAD_PATH.unshift(cookbook_vendor_path)100        require 'chef-server/fetcher'101      end102      def load_automate_fetcher103        Chef::Log.debug "Load Chef Automate fetcher from: #{cookbook_vendor_path}"104        $LOAD_PATH.unshift(cookbook_vendor_path)105        require 'chef-automate/fetcher'106      end107      # sets format to json-min when chef-compliance, json when chef-automate108      def get_opts(format, quiet, attributes)109        output = quiet ? ::File::NULL : $stdout110        Chef::Log.debug "Format is #{format}"111        opts = {112          'report' => true,113          'format' => format,114          'output' => output,115          'logger' => Chef::Log, # Use chef-client log level for inspec run,116          backend_cache: node['audit']['inspec_backend_cache'],117          attributes: attributes,118        }119        opts...linux_updates.rb
Source:linux_updates.rb  
1# -*- encoding : utf-8 -*-2# copyright: 2016, Christoph Hartmann3# copyright: 2016, Dominik Richter4# license: MPLv25#6# This Source Code Form is subject to the terms of the Mozilla Public7# License, v. 2.0. If a copy of the MPL was not distributed with this8# file, You can obtain one at http://mozilla.org/MPL/2.0/.9require 'json'10require 'rexml/document'11class LinuxUpdateManager < Inspec.resource(1)12  name 'linux_update'13  desc 'Use the linux_update InSpec audit resource to test for available or installed updates'14  # def initialize15  #   if inspec.os.redhat?16  #     @update_mgmt = RHELUpdateFetcher.new(inspec)17  #   elsif inspec.os.debian?18  #     @update_mgmt = UbuntuUpdateFetcher.new(inspec)19  #   end20  #   return skip_resource 'The `linux_update` resource is not supported on your OS.' if @update_mgmt.nil?21  # end22  # Since Amazon Linux is based on RedHat, they may use the same method.23  def initialize24    case inspec.os[:family]25    when 'redhat', 'amazon'26      @update_mgmt = RHELUpdateFetcher.new(inspec)27    when 'debian'28      @update_mgmt = UbuntuUpdateFetcher.new(inspec)29    when 'suse'30      @update_mgmt = SuseUpdateFetcher.new(inspec)31    end32    skip_resource 'The `linux_update` resource is not supported on your OS.' if @update_mgmt.nil?33  end34  def updates35    return [] if @update_mgmt.nil?36    u = @update_mgmt.updates37    return [] if u.nil? || u.empty?38    u['available']39  end40  def uptodate?41    return nil if @update_mgmt.nil?42    u = @update_mgmt.updates43    return false if u.nil? || !u['available'].empty?44    l = @update_mgmt.patches45    return false if l.nil? || !l.empty?46    true47  end48  def packages49    return [] if @update_mgmt.nil?50    p = @update_mgmt.packages51    return [] if p.nil? || p.empty?52    p['installed']53  end54  def patches55    return [] if @update_mgmt.nil?56    @update_mgmt.patches || []57  end58  def to_s59    'Linux Update'60  end61end62class UpdateFetcher63  def initialize(inspec)64    @inspec = inspec65  end66  def packages67    []68  end69  def updates70    []71  end72  def patches73    []74  end75  def parse_json(script)76    cmd = @inspec.bash(script)77    begin78      JSON.parse(cmd.stdout)79    rescue JSON::ParserError => _e80      return []81    end82  end83end84PatchEntry = Struct.new(:name, :version, :arch, :category, :severity) do85  def to_s86    r = "System Patch #{name} (v#{version} #{arch}"87    r+= ", #{category}" unless category.nil?88    r+= ", #{severity}" unless severity.nil?89    r + ')'90  end91end92class SuseUpdateFetcher < UpdateFetcher93  def patches94    out = zypper_xml('list-updates -t patch')95    xml = REXML::Document.new(out)96    extract_xml_updates(REXML::XPath.first(xml, '//update-list')) +97      extract_xml_updates(REXML::XPath.first(xml, '//blocked-update-list'))98  end99  def updates100    out = zypper_xml('list-updates')101    xml = REXML::Document.new(out)102    res = extract_xml_updates(REXML::XPath.first(xml, '//update-list')) +103          extract_xml_updates(REXML::XPath.first(xml, '//blocked-update-list'))104    { 'available' => res }105  end106  private107  def zypper_xml(cmd)108    out = @inspec.command('zypper --xmlout '+cmd)109    if out.exit_status != 0110      fail_resource('Cannot retrieve package updates from the OS: '+out.stderr)111    end112    out.stdout.force_encoding('UTF-8')113  end114  def extract_xml_updates(updates_el)115    res = []116    return res if updates_el.nil?117    REXML::XPath.each(updates_el, 'update') do |el|118      a = el.attributes119      res.push(120        PatchEntry.new(a['name'], a['edition'], a['arch'], a['category'], a['severity']),121      )122    end123    res124  end125end126class UbuntuUpdateFetcher < UpdateFetcher127  def packages128    ubuntu_packages = ubuntu_base + <<-PRINT_JSON129echo -n '{"installed":['130dpkg-query -W -f='${Status}\\t${Package}\\t${Version}\\t${Architecture}\\n' |\\131  grep '^install ok installed\\s' |\\132  awk '{ printf "{\\"name\\":\\""$4"\\",\\"version\\":\\""$5"\\",\\"arch\\":\\""$6"\\"}," }' | rev | cut -c 2- | rev | tr -d '\\n'133echo -n ']}'134PRINT_JSON135    parse_json(ubuntu_packages)136  end137  def updates138    ubuntu_updates = ubuntu_base + <<-PRINT_JSON139echo -n '{"available":['140DEBIAN_FRONTEND=noninteractive apt-get upgrade --dry-run | grep Inst | tr -d '[]()' |\\141  awk '{ printf "{\\"name\\":\\""$2"\\",\\"version\\":\\""$4"\\",\\"repo\\":\\""$5"\\",\\"arch\\":\\""$6"\\"}," }' | rev | cut -c 2- | rev | tr -d '\\n'142echo -n ']}'143PRINT_JSON144    parse_json(ubuntu_updates)145  end146  private147  def ubuntu_base148    base = <<-PRINT_JSON149#!/bin/sh150DEBIAN_FRONTEND=noninteractive apt-get update >/dev/null 2>&1151readlock() { cat /proc/locks | awk '{print $5}' | grep -v ^0 | xargs -I {1} find /proc/{1}/fd -maxdepth 1 -exec readlink {} \\; | grep '^/var/lib/dpkg/lock$'; }152while test -n "$(readlock)"; do sleep 1; done153echo " "154PRINT_JSON155    base156  end157end158class RHELUpdateFetcher < UpdateFetcher159  def packages160    rhel_packages = <<-PRINT_JSON161sleep 2 && echo " "162echo -n '{"installed":['163rpm -qa --queryformat '"name":"%{NAME}","version":"%{VERSION}-%{RELEASE}","arch":"%{ARCH}"\\n' |\\164  awk '{ printf "{"$1"}," }' | rev | cut -c 2- | rev | tr -d '\\n'165echo -n ']}'166PRINT_JSON167    parse_json(rhel_packages)168  end169  def updates170    rhel_updates = <<-PRINT_JSON171#!/bin/sh172python -c 'import sys; sys.path.insert(0, "/usr/share/yum-cli"); import cli; ybc = cli.YumBaseCli(); ybc.setCacheDir("/tmp"); list = ybc.returnPkgLists(["updates"]);res = ["{\\"name\\":\\""+x.name+"\\", \\"version\\":\\""+x.version+"-"+x.release+"\\",\\"arch\\":\\""+x.arch+"\\",\\"repository\\":\\""+x.repo.id+"\\"}" for x in list.updates]; print "{\\"available\\":["+",".join(res)+"]}"'173PRINT_JSON174    cmd = @inspec.bash(rhel_updates)175    unless cmd.exit_status == 0176      # essentially we want https://github.com/chef/inspec/issues/1205177      STDERR.puts 'Could not determine patch status.'178      return nil179    end180    first = cmd.stdout.index('{')181    res = cmd.stdout.slice(first, cmd.stdout.size - first)182    begin183      JSON.parse(res)184    rescue JSON::ParserError => _e185      return []186    end187  end188end...fetcher
Using AI Code Generation
1  its('name') { should eq 'local' }2  its('name') { should eq 'local' }3  its('name') { should eq 'local' }4  its('name') { should eq 'local' }5  its('name') { should eq 'local' }6  its('name') { should eq 'local' }7  its('name') { should eq 'local' }8  its('name') { should eq 'local' }9  its('name') { should eq 'local' }10  its('name') { should eq 'local' }11  its('name') { should eq 'local' }12  its('name') { should eq 'local' }13  its('name') { should eq 'local'fetcher
Using AI Code Generation
1    it { should be_a_kind_of Inspec::Fetcher }2    it { should be_a_kind_of Inspec::Fetcher }3    it { should be_a_kind_of Inspec::Fetcher }4    it { should be_a_kind_of Inspec::Fetcher }5    it { should be_a_kind_of Inspec::Fetcher }6    it { should be_a_kind_of Inspec::Fetcher }7    it { should be_a_kind_of Inspec::Fetcher }8    it { should be_a_kind_of Inspec::Fetcher }9    it { should be_a_kind_of Inspec::Fetcher }fetcher
Using AI Code Generation
1    it { should be_a String }2    it { should be_a String }3    it { should be_a String }4    it { should be_a String }fetcher
Using AI Code Generation
1inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')2inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')3inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/proiilb.ear.gz')4inspe .fetci(target:n'ssh://user@host/path/to/profile.tar.gz')5inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/protche.tar.gz')6inspec.fetch(target:r'ssh://user@host/path/to/pro ile.tar.gz')7inspec =Inspec::Fetcher.resolve(taret: 'ssh://user@host/path/to/profle.tar.gz')8inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')9inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')10inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')11inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')12inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')13inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')14inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')fetcher
Using AI Code Generation
1inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')2inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')3inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')4inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')5inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')6inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')7inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')8inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')fetcher
Using AI Code Generation
1fetcher = Inspec.fetcher(transport_name)2fetcher = Inspec.fetcher(transport_name)3fetcher = Inspec.fetcher(transport_name)4fetcher = Inspec.fetcher(transport_name)5fetcher = Inspec.fetcher(transport_name)6  its('name') { should eq 'local' }7  its('name') { should eq 'local' }8  its('name') { should eq 'local' }9  its('name') { should eq 'local' }10  its('name') { should eq 'local' }11  its('name') { should eq 'local' }12  its('name') { should eq 'local' }13  its('name') { should eq 'local' }14  its('name') { should eq 'local' }15  its('name') { should eq 'local' }16  its('name') { should eq 'local' }17  its('name') { should eq 'local'fetcher
Using AI Code Generation
1    it { should be_a_kind_of Inspec::Fetcher }2    it { should be_a_kind_of Inspec::Fetcher }3    it { should be_a_kind_of Inspec::Fetcher }4    it { should be_a_kind_of Inspec::Fetcher }5    it { should be_a_kind_of Inspec::Fetcher }6    it { should be_a_kind_of Inspec::Fetcher }7    it { should be_a_kind_of Inspec::Fetcher }8    it { should be_a_kind_of Inspec::Fetcher }9    it { should be_a_kind_of Inspec::Fetcher }fetcher
Using AI Code Generation
1    it { should be_a String }2    it { should be_a String }3    it { should be_a String }4    it { should be_a String }fetcher
Using AI Code Generation
1inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')2inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')3inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')4inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')5inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')6inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')7inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')8inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')9inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')10inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')11inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')12inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')13inspec = Inspec::Fetcher.resolve(target: 'ssh://user@host/path/to/profile.tar.gz')14inspec.fetch(target: 'ssh://user@host/path/to/profile.tar.gz')fetcher
Using AI Code Generation
1inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')2inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')3inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')4inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')5inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')6inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')7inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')8inspec = Inspec::Fetcher.resolve('file:///path/to/archive.tar.gz')fetcher
Using AI Code Generation
1fetcher = Inspec.fetcher(transport_name)2fetcher = Inspec.fetcher(transport_name)3fetcher = Inspec.fetcher(transport_name)4fetcher = Inspec.fetcher(transport_name)5fetcher = Inspec.fetcher(transport_name)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!!
