Best Inspec_ruby code snippet using Inspec.resource
archer.rb
Source:archer.rb  
1# encoding: utf-82require 'inspec/utils/filter'3require 'hashie/mash'4require 'inspec/resources/package'5# needed to skip cert verification when ssl_verify false6# this can be replaced with -SkipCertificateCheck in Powershell 6.x7SKIP_CERT_CHECK = %(8add-type @"9    using System.Net;10    using System.Security.Cryptography.X509Certificates;11    public class TrustAllCertsPolicy : ICertificatePolicy {12        public bool CheckValidationResult(13            ServicePoint srvPoint, X509Certificate certificate,14            WebRequest request, int certificateProblem) {15            return true;16        }17    }18"@19[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy20[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls1221)22LOGIN_PATH = '/api/core/security/login'.freeze23SECURITY_PARAMETERS_PATH = '/api/core/system/securityparameter'.freeze24class Archer < Inspec.resource(1)25  name 'archer'26  desc "Use the RSA Archer InSpec audit resource to test the status your RSA Archer system."27  example "28    describe archer(url: attribute('url'),29                               instancename: attribute('instancename'),30                               user_domain: attribute('user_domain'),31                               username: attribute('username'),32                               password: attribute('password'),33                               ssl_verify: attribute('ssl_verify')) do34      its('default_administrative_user.MinPasswordLength') { should cmp >= 9 }35      its('general_user_parameter.MinPasswordLength') { should cmp >= 9 }36      its('archer_services_parameter.MinPasswordLength') { should cmp >= 9 }37    end38  "39  attr_reader40  def initialize(opts = {})41    unless inspec.command('curl').exist?42      raise Inspec::Exceptions::ResourceSkipped, "Package `curl` and `powershell` not avaiable on the host"43    end44    @url = opts.fetch(:url, 'https://localhost/')45    @creds = {}46    @creds['InstanceName']      = opts.fetch(:instancename, nil)47    @creds['Username']      = opts.fetch(:username, nil)48    @creds['UserDomain'] = opts.fetch(:userdomain, nil)49    @creds['Password']   = opts.fetch(:password, nil)50    @ssl_verify = opts.fetch(:ssl_verify, true)51    login if session_token.nil?52  end53  def to_s54    "Archer Instance #{@creds['InstanceName']}"55  end56  def default_administrative_user57    content = securityparameter[0]58    verify_json_payload!(content)59    Hashie::Mash.new(content['RequestedObject'])60  end61  def general_user_parameter62    content = securityparameter[1]63    verify_json_payload!(content)64    Hashie::Mash.new(content['RequestedObject'])65  end66  def archer_services_parameter67    content = securityparameter[2]68    verify_json_payload!(content)69    Hashie::Mash.new(content['RequestedObject'])70  end71  def curl_command(request: nil, headers: nil, body: nil, path: nil)72    cmd_string = ['curl']73    cmd_string << '-k' unless @ssl_verify74    cmd_string << "-X #{request}" unless request.nil?75    cmd_string << headers.map { |x, y| "-H \"#{x}\":\"#{y}\"" }.join(' ') unless headers.nil?76    cmd_string << "-H 'Content-Type: application/json'"77    cmd_string << "-d '#{body.to_json}'" unless body.nil?78    cmd_string << URI.join(@url, path)79    cmd_string.join(' ')80  end81  def invoke_restmethod_command(request: nil, headers: nil, body: nil, path: nil)82    cmd_string = ['Invoke-RestMethod']83    cmd_string << "-Method #{request}" unless request.nil?84    cmd_string << "-Headers @{#{headers.map { |x, y| " '#{x}' = '#{y}'" }.join(';')} }" unless headers.nil?85    cmd_string << "-ContentType 'application/json'"86    cmd_string << "-Body '#{body.to_json}'" unless body.nil?87    cmd_string << URI.join(@url, path)88    cmd_string << '| ConvertTo-Json'89    return "#{SKIP_CERT_CHECK} \n #{cmd_string.join(' ')}" unless @ssl_verify90    cmd_string.join(' ')91  end92  def parse_response(response)93    JSON.parse(response)94  rescue JSON::ParserError => e95    raise Inspec::Exceptions::ResourceSkipped, "Error Parsing JSON response from Archer: #{ e.message}."96  end97  def session_token=(token)98    ENV['INSPEC_ARCHER_SESSION_TOKEN'] = token99  end100  def session_token101    ENV['INSPEC_ARCHER_SESSION_TOKEN']102  end103  def login104    if inspec.os.windows?105      cmd = invoke_restmethod_command(request: 'POST',106                                      headers: nil,107                                      body: @creds,108                                      path: LOGIN_PATH)109      response = inspec.powershell(cmd)110      verify_pwsh_success!(response)111    else112      cmd = curl_command(request: 'POST',113                         headers: nil,114                         body: @creds,115                         path: LOGIN_PATH)116      response = inspec.command(cmd)117      verify_curl_success!(response)118    end119    content = parse_response(response.stdout)120    verify_json_payload!(content)121    ENV['INSPEC_ARCHER_SESSION_TOKEN'] = content['RequestedObject']['SessionToken']122  end123  def securityparameter124    headers = { 'Authorization' => "Archer session-id=#{session_token}" }125    if inspec.os.windows?126      cmd = invoke_restmethod_command(request: 'GET',127                                      headers: headers,128                                      body: nil,129                                      path: SECURITY_PARAMETERS_PATH)130      response = inspec.powershell(cmd)131      verify_pwsh_success!(response)132      parse_response(response.stdout)['value']133    else134      cmd = curl_command(request: 'GET',135                         headers: headers,136                         body: nil,137                         path: SECURITY_PARAMETERS_PATH)138      response = inspec.command(cmd)139      verify_curl_success!(response)140      parse_response(response.stdout)141    end142  end143  def verify_curl_success!(cmd)144    raise Inspec::Exceptions::ResourceSkipped, "Error fetching Archer data from curl #{@url}\nError: #{cmd.stderr.match(/curl: \(\d.\).*$/)}" unless cmd.exit_status.zero?145  end146  def verify_pwsh_success!(cmd)147    if cmd.stderr =~ /No HTTP resource was found that matches the request URI|DNS_FAIL/148      raise Inspec::Exceptions::ResourceSkipped, "Connection refused - please check the URL #{@url} for accuracy"149    end150    if cmd.stderr =~ /Could not establish trust relationship for the SSL\/TLS secure channel/151      raise Inspec::Exceptions::ResourceSkipped, 'Connection refused - peer certificate issuer is not recognized; try setting ssl_verify to false'152    end153    raise Inspec::Exceptions::ResourceSkipped, "Error fetching Archer data from Invoke-RestMethod #{@url}: #{cmd.stderr}" unless cmd.exit_status.zero?154  end155  def verify_json_payload!(content)156    raise Inspec::Exceptions::ResourceSkipped, "Message: #{content['ValidationMessages'][0]['MessageKey']}" unless content['IsSuccessful']#{url}\nError: #{cmd.stderr.match(/curl: \(\d.\).*$/)}""157  end158end...inspec_gem.rb
Source:inspec_gem.rb  
1provides :inspec_gem2resource_name :inspec_gem3property :gem_name, String, name_property: true4property :version, String5property :source, String6default_action :install7action :install do8  # detect if installation is required9  compatible_version = compatible_with_client?(new_resource.version)10  installation_required = inspec_info.nil? || !new_resource.version.nil?11  # detect if the same version is already installed12  unless inspec_info.nil?13    installed_version = inspec_info.version.to_s14    Chef::Log.debug("Installed Chef-InSpec version: #{installed_version}")15    if new_resource.version == installed_version16      installation_required = false17      Chef::Log.info("inspec_gem: not installing Chef-InSpec. Requested version #{new_resource.version} already installed")18      return19    end20  end21  if installation_required && compatible_version22    Chef::Log.info("Installation of Chef-InSpec required: #{installation_required}")23    unless inspec_info.nil?24      converge_by 'uninstall all inspec and train gem versions' do25        uninstall_inspec_gem26      end27    end28    converge_by 'install given Chef-InSpec version' do29      install_inspec_gem(version: new_resource.version, source: new_resource.source)30    end31  elsif new_resource.version.nil?32    Chef::Log.info('inspec_gem: not installing Chef-InSpec. No Chef-Inspec version specified')33  elsif !compatible_version34    Chef::Log.warn("inspec_gem: not installing Chef-InSpec. Requested version #{new_resource.version} is not compatible with chef-client #{Chef::VERSION}")35  end36end37action_class do38  def install_inspec_gem(options)39    gem_source  = options[:source]40    gem_version = options[:version]41    gem_version = nil if gem_version == 'latest'42    # use inspec-core for recent inspec versions43    gem_name = use_inspec_core?(gem_version) ? 'inspec-core' : 'inspec'44    chef_gem gem_name do45      version gem_version unless gem_version.nil?46      unless gem_source.nil?47        clear_sources true48        include_default_source false if respond_to?(:include_default_source)...erb_helpers.rb
Source:erb_helpers.rb  
...20    # @return [String] Contents of the file21    def remote_file_content(remote_file)22      runner.backend.backend.file(remote_file).content23    end24    # Allow access to all InSpec resources from the report.25    #26    # @return [Inspec::Backend] The InSpec backend27    def inspec_resource28      runner.backend29    end30    # Return InSpec OS resource results.31    #32    # @return [Class] Look into documentation for properties (.arch/.family/.name/...)33    # @see https://github.com/inspec/inspec/blob/master/lib/inspec/resources/os.rb34    def os35      runner.backend.os36    end37    # Return InSpec SysInfo resource results.38    #39    # @return [Class] Look into documentation for properteis (.domain/.fqdn/.hostname/.ip_address/.model/...)40    # @see https://github.com/inspec/inspec/blob/master/lib/inspec/resources/sys_info.rb41    def sys_info42      runner.backend.sys_info43    end44    # Return if all results of a control have passed/skipped/waived.45    #46    # @param [Hash] control Data of a control run47    # @return [Boolean] If all passed checks48    def control_passed?(control)49      control[:results].any? { |result| result[:status] == "failed" }50    end51    # Map InSpec status to cleartext52    #53    # @param [String] inspec_status One of the valid InSpec result status.54    # @return [Strint] "ok"/"not ok" depending on status...resource
Using AI Code Generation
1describe file('/tmp/file.txt') do2  it { should exist }3describe file('/tmp/file.txt') do4  it { should exist }5describe file('/tmp/file.txt') do6  it { should exist }7describe file('/tmp/file.txt') do8  it { should exist }9describe file('/tmp/file.txt') do10  it { should exist }11describe file('/tmp/file.txt') do12  it { should exist }13describe file('/tmp/file.txt') do14  it { should exist }15describe file('/tmp/file.txt') do16  it { should exist }17describe file('/tmp/file.txt') do18  it { should exist }19describe file('/tmp/file.txt') do20  it { should exist }21describe file('/tmp/file.txt') do22  it { should exist }23describe file('/tmp/file.txt') do24  it { should exist }25describe file('/tmp/file.txt') do26  it { should exist }27describe file('/tmp/file.txt') do28  it { should exist }29describe file('/tmp/file.txt') doresource
Using AI Code Generation
1describe file('/etc/ssh/sshd_config') do2  its('content') { should match(/PermitRootLogin no/) }3describe file('/etc/ssh/sshd_config') do4  its('content') { should match(/PermitRootLogin yes/) }5describe file('/etc/ssh/sshd_config') do6  its('content') { should match(/PermitRootLogin yes/) }7describe file('/etc/ssh/sshd_config') do8  its('content') { should match(/PermitRootLogin yes/) }9describe file('/etc/ssh/sshd_config') do10  its('content') { should match(/PermitRootLogin yes/) }11describe file('/etc/ssh/sshd_config') do12  its('content') { should match(/PermitRootLogin yes/) }13describe file('/etc/ssh/sshd_config') do14  its('content') { should match(/PermitRootLogin yes/) }15describe file('/etc/ssh/sshd_config') do16  its('content') { should match(/PermitRootLogin yes/) }17describe file('/etc/ssh/sshd_config') do18  its('content') { should match(/PermitRootLogin yes/) }19describe file('/etc/ssh/sshd_config') do20  its('content') { should match(/PermitRootLogin yes/) }21describe file('/etc/ssh/sshd_config') do22  its('content') {resource
Using AI Code Generation
1  describe resource('file', '/etc/passwd') do2    it { should exist }3    its('mode') { should cmp '0644' }4  describe resource('file', '/etc/passwd') do5    it { should exist }6    its('mode') { should cmp '0644' }7  describe resource('file', '/etc/passwd') do8    it { should exist }9    its('mode') { should cmp '0644' }10  describe resource('file', '/etc/passwd') do11    it { should exist }12    its('mode') { should cmp '0644' }13  describe resource('file', '/etc/passwd') do14    it { should exist }15    its('mode') { should cmp '0644' }16  describe resource('file', '/etc/passwd') do17    it { should exist }18    its('mode') { should cmp '0644' }19  describe resource('file', '/etc/passwd') do20    it { should exist }21    its('mode') { should cmp '0644' }22  describe resource('file', '/etc/passwd') do23    it { should exist }24    its('mode') { should cmp '0644' }25  describe resource('resource
Using AI Code Generation
1describe resource('file', '/tmp') do2  it { should exist }3  its('mode') { should cmp '0755' }4describe file('/tmp') do5  it { should exist }6  its('mode') { should cmp '0755' }7describe file('/tmp') do8  it { should exist }9  its('mode') { should cmp '0755' }10describe file('/tmp') do11  it { should exist }12  its('mode') { should cmp '0755' }13describe file('/tmp') do14  it { should exist }15  its('mode') { should cmp '0755' }16describe file('/tmp') do17  it { should exist }18  its('mode') { should cmp '0755' }19describe file('/tmp') do20  it { should exist }21  its('mode') { should cmp '0755' }22describe file('/tmp') do23  it { should exist }24  its('mode') { should cmp '0755' }25describe file('/tmp') do26  it { should exist }27  its('mode') { should cmp '0755' }28describe file('/tmp') do29  it { should exist }30  its('mode') { should cmp '0755' }31describe file('/tmp') do32  it { should exist }33  its('mode') { should cmp '0755' }34describe file('/tmp') do35  it { should exist }36  its('mode') { should cmp '0755' }resource
Using AI Code Generation
1  describe file('/tmp/test.txt') do2    it { should exist }3  describe file('/tmp/test.txt') do4    it { should exist }5  describe file('/tmp/test.txt') do6    it { should exist }7  describe file('/tmp/test.txt') do8    it { should exist }9  describe file('/tmp/test.txt') do10    it { should exist }11  describe file('/tmp/test.txt') do12    it { should exist }13  describe file('/tmp/test.txt') do14    it { should exist }15  describe file('/tmp/test.txt') doresource
Using AI Code Generation
1describe file('/tmp') do2  it { should exist }3describe file('/tmp') do4  it { should exist }5describe file('/tmp') do6  it { should exist }7describe file('/tmp') do8  it { should exist }9describe file('/tmp') do10  it { should exist }11describe file('/tmp') do12  it { should exist }13describe file('/tmp') do14  it { should exist }15describe file('/tmp') do16  it { should exist }17describe file('/tmp') do18  it { should exist }19describe file('/tmp') do20  it { should exist }21describe file('/tmp') do22  it { should exist }23describe file('/tmp') do24  it { should exist }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!!
