How to use for_command method of Inspec Package

Best Inspec_ruby code snippet using Inspec.for_command

config.rb

Source:config.rb Github

copy

Full Screen

...34 end35 # This gets called when the first config is created.36 def initialize(cli_opts = {}, cfg_io = nil, command_name = nil)37 @command_name = command_name || (ARGV.empty? ? nil : ARGV[0].to_sym)38 @defaults = Defaults.for_command(@command_name)39 @cli_opts = cli_opts.dup40 cfg_io = resolve_cfg_io(@cli_opts, cfg_io)41 @cfg_file_contents = read_cfg_file_io(cfg_io)42 @merged_options = merge_options43 @final_options = finalize_options44 self.class.cached = self45 end46 def diagnose47 return unless self[:diagnose]48 puts "InSpec version: #{Inspec::VERSION}"49 puts "Train version: #{Train::VERSION}"50 puts 'Command line configuration:'51 pp @cli_opts52 puts 'JSON configuration file:'53 pp @cfg_file_contents54 puts 'Merged configuration:'55 pp @merged_options56 puts57 end58 #-----------------------------------------------------------------------#59 # Train Credential Handling60 #-----------------------------------------------------------------------#61 # Returns a Hash with Symbol keys as follows:62 # backend: machine name of the Train transport needed63 # If present, any of the GENERIC_CREDENTIALS.64 # All other keys are specific to the backend.65 #66 # The credentials are gleaned from:67 # * the Train transport defaults. Train handles this on transport creation,68 # so this method doesn't load defaults.69 # * individual InSpec CLI options (which in many cases may have the70 # transport name prefixed, which is stripped before being added71 # to the creds hash)72 # * the --target CLI option, which is interpreted:73 # - as a transport://credset format, which looks up the creds in74 # the config file in the credentials section75 # - as an arbitrary URI, which is parsed by Train.unpack_target_from_uri76 def unpack_train_credentials77 # Internally, use indifferent access while we build the creds78 credentials = Thor::CoreExt::HashWithIndifferentAccess.new({})79 # Helper methods prefixed with _utc_ (Unpack Train Credentials)80 credentials.merge!(_utc_generic_credentials)81 _utc_determine_backend(credentials)82 transport_name = credentials[:backend].to_s83 _utc_merge_credset(credentials, transport_name)84 _utc_merge_transport_options(credentials, transport_name)85 # Convert to all-Symbol keys86 credentials.each_with_object({}) do |(option, value), creds|87 creds[option.to_sym] = value88 creds89 end90 end91 private92 def _utc_merge_transport_options(credentials, transport_name)93 # Ask Train for the names of the transport options94 transport_options = Train.options(transport_name).keys.map(&:to_s)95 # If there are any options with those (unprefixed) names, merge them in.96 unprefixed_transport_options = final_options.select do |option_name, _value|97 transport_options.include? option_name # e.g., 'host'98 end99 credentials.merge!(unprefixed_transport_options)100 # If there are any prefixed options, merge them in, stripping the prefix.101 transport_prefix = transport_name.downcase.tr('-', '_') + '_'102 transport_options.each do |bare_option_name|103 prefixed_option_name = transport_prefix + bare_option_name.to_s104 if final_options.key?(prefixed_option_name)105 credentials[bare_option_name.to_s] = final_options[prefixed_option_name]106 end107 end108 end109 # fetch any info that applies to all transports (like sudo information)110 def _utc_generic_credentials111 @final_options.select { |option, _value| GENERIC_CREDENTIALS.include?(option) }112 end113 def _utc_determine_backend(credentials)114 return if credentials.key?(:backend)115 # Default to local116 unless @final_options.key?(:target)117 credentials[:backend] = 'local'118 return119 end120 # Look into target121 %r{^(?<transport_name>[a-z_\-0-9]+)://.*$} =~ final_options[:target]122 unless transport_name123 raise ArgumentError, "Could not recognize a backend from the target #{final_options[:target]} - use a URI format with the backend name as the URI schema. Example: 'ssh://somehost.com' or 'transport://credset' or 'transport://' if credentials are provided outside of InSpec."124 end125 credentials[:backend] = transport_name.to_s # these are indeed stored in Train as Strings.126 end127 def _utc_merge_credset(credentials, transport_name)128 # Look for Config File credentials/transport_name/credset129 credset_name = _utc_find_credset_name(credentials, transport_name)130 if credset_name131 credset = @cfg_file_contents.dig('credentials', transport_name, credset_name)132 if credset133 credentials.merge!(credset)134 else135 # OK, we had a target that looked like transport://something136 # But we don't know what that something is - there was no137 # matching credset with it. Let train parse it.138 credentials.merge!(Train.unpack_target_from_uri(final_options[:target]))139 end140 elsif final_options.key?(:target)141 # Not sure what target looked like at all!142 # Let train parse it.143 credentials.merge!(Train.unpack_target_from_uri(final_options[:target]))144 end145 end146 def _utc_find_credset_name(_credentials, transport_name)147 return nil unless final_options[:target]148 match = final_options[:target].match(%r{^#{transport_name}://(?<credset_name>[\w\d\-]+)$})149 match ? match[:credset_name] : nil150 end151 #-----------------------------------------------------------------------#152 # Reading Config Files153 #-----------------------------------------------------------------------#154 # Regardless of our situation, end up with a readable IO object155 def resolve_cfg_io(cli_opts, cfg_io)156 raise(ArgumentError, 'Inspec::Config must use an IO to read from') if cfg_io && !cfg_io.respond_to?(:read)157 cfg_io ||= check_for_piped_config(cli_opts)158 return cfg_io if cfg_io159 path = determine_cfg_path(cli_opts)160 cfg_io = File.open(path) if path161 cfg_io || StringIO.new('{ "version": "1.1" }')162 end163 def check_for_piped_config(cli_opts)164 cli_opt = cli_opts[:config] || cli_opts[:json_config]165 Inspec.deprecate(:cli_option_json_config) if cli_opts.key?(:json_config)166 return nil unless cli_opt167 return nil unless cli_opt == '-'168 # This warning is here so that if a user invokes inspec with --config=-,169 # they will have an explanation for why it appears to hang.170 Inspec::Log.warn 'Reading JSON config from standard input' if STDIN.tty?171 STDIN172 end173 def determine_cfg_path(cli_opts)174 path = cli_opts[:config] || cli_opts[:json_config]175 Inspec.deprecate(:cli_option_json_config) if cli_opts.key?(:json_config)176 if path.nil?177 default_path = File.join(Inspec.config_dir, 'config.json')178 path = default_path if File.exist?(default_path)179 elsif !File.exist?(path)180 raise ArgumentError, "Could not read configuration file at #{path}"181 end182 path183 end184 # When reading STDIN, read it once into a class variable and cache it.185 # Don't cache other IO objects though, as we use several different StringIOs186 # during unit testing. Refs #3792187 def self.stdin_contents # rubocop: disable Lint/IneffectiveAccessModifier188 @stdin_content ||= STDIN.read189 end190 def read_cfg_file_io(cfg_io)191 contents = cfg_io == STDIN ? self.class.stdin_contents : cfg_io.read192 begin193 @cfg_file_contents = JSON.parse(contents)194 validate_config_file_contents!195 rescue JSON::ParserError => e196 raise Inspec::ConfigError::MalformedJson, "Failed to load JSON configuration: #{e}\nConfig was: #{contents}"197 end198 @cfg_file_contents199 end200 def file_version201 @cfg_file_contents['version'] || :legacy202 end203 def legacy_file?204 file_version == :legacy205 end206 def config_file_cli_options207 if legacy_file?208 # Assume everything in the file is a CLI option209 @cfg_file_contents210 else211 @cfg_file_contents['cli_options'] || {}212 end213 end214 def config_file_reporter_options215 # This is assumed to be top-level in both legacy and 1.1.216 # Technically, you could sneak it in the 1.1 cli opts area.217 @cfg_file_contents.key?('reporter') ? { 'reporter' => @cfg_file_contents['reporter'] } : {}218 end219 #-----------------------------------------------------------------------#220 # Validation221 #-----------------------------------------------------------------------#222 def validate_config_file_contents!223 version = @cfg_file_contents['version']224 # Assume legacy format, which is unconstrained225 return unless version226 unless version == '1.1'227 raise Inspec::ConfigError::Invalid, "Unsupported config file version '#{version}' - currently supported versions: 1.1"228 end229 valid_fields = %w{version cli_options credentials compliance reporter}.sort230 @cfg_file_contents.keys.each do |seen_field|231 unless valid_fields.include?(seen_field)232 raise Inspec::ConfigError::Invalid, "Unrecognized top-level configuration field #{seen_field}. Recognized fields: #{valid_fields.join(', ')}"233 end234 end235 end236 def validate_reporters!(reporters)237 return if reporters.nil?238 # TODO: move this into a reporter plugin type system239 valid_types = [240 'automate',241 'cli',242 'documentation',243 'html',244 'json',245 'json-automate',246 'json-min',247 'json-rspec',248 'junit',249 'progress',250 'yaml',251 ]252 reporters.each do |reporter_name, reporter_config|253 raise NotImplementedError, "'#{reporter_name}' is not a valid reporter type." unless valid_types.include?(reporter_name)254 next unless reporter_name == 'automate'255 %w{token url}.each do |option|256 raise Inspec::ReporterError, "You must specify a automate #{option} via the config file." if reporter_config[option].nil?257 end258 end259 # check to make sure we are only reporting one type to stdout260 stdout_reporters = 0261 reporters.each_value do |reporter_config|262 stdout_reporters += 1 if reporter_config['stdout'] == true263 end264 raise ArgumentError, 'The option --reporter can only have a single report outputting to stdout.' if stdout_reporters > 1265 end266 #-----------------------------------------------------------------------#267 # Merging Options268 #-----------------------------------------------------------------------#269 def merge_options270 options = Thor::CoreExt::HashWithIndifferentAccess.new({})271 # Lowest precedence: default, which may vary by command272 options.merge!(@defaults)273 # Middle precedence: merge in any CLI options defined from the config file274 options.merge!(config_file_cli_options)275 # Reporter options may be defined top-level.276 options.merge!(config_file_reporter_options)277 # Highest precedence: merge in any options defined via the CLI278 options.merge!(@cli_opts)279 options280 end281 #-----------------------------------------------------------------------#282 # Finalization283 #-----------------------------------------------------------------------#284 def finalize_options285 options = @merged_options.dup286 finalize_set_top_level_command(options)287 finalize_parse_reporters(options)288 finalize_handle_sudo(options)289 finalize_compliance_login(options)290 Thor::CoreExt::HashWithIndifferentAccess.new(options)291 end292 def finalize_set_top_level_command(options)293 options[:type] = @command_name294 Inspec::BaseCLI.inspec_cli_command = @command_name # TODO: move to a more relevant location295 end296 def finalize_parse_reporters(options) # rubocop:disable Metrics/AbcSize297 # default to cli report for ad-hoc runners298 options['reporter'] = ['cli'] if options['reporter'].nil?299 # parse out cli to proper report format300 if options['reporter'].is_a?(Array)301 reports = {}302 options['reporter'].each do |report|303 reporter_name, destination = report.split(':', 2)304 if destination.nil? || destination.strip == '-'305 reports[reporter_name] = { 'stdout' => true }306 else307 reports[reporter_name] = {308 'file' => destination,309 'stdout' => false,310 }311 reports[reporter_name]['target_id'] = options['target_id'] if options['target_id']312 end313 end314 options['reporter'] = reports315 end316 # add in stdout if not specified317 if options['reporter'].is_a?(Hash)318 options['reporter'].each do |reporter_name, config|319 options['reporter'][reporter_name] = {} if config.nil?320 options['reporter'][reporter_name]['stdout'] = true if options['reporter'][reporter_name].empty?321 options['reporter'][reporter_name]['target_id'] = options['target_id'] if options['target_id']322 end323 end324 validate_reporters!(options['reporter'])325 options326 end327 def finalize_handle_sudo(options)328 # Due to limitations in Thor it is not possible to set an argument to be329 # both optional and its value to be mandatory. E.g. the user supplying330 # the --password argument is optional and not always required, but331 # whenever it is used, it requires a value. Handle options that were332 # defined in such a way and require a value here:333 %w{password sudo-password}.each do |option_name|334 snake_case_option_name = option_name.tr('-', '_').to_s335 next unless options[snake_case_option_name] == -1 # Thor sets -1 for missing value - see #1918336 raise ArgumentError, "Please provide a value for --#{option_name}. For example: --#{option_name}=hello."337 end338 # Infer `--sudo` if using `--sudo-password` without `--sudo`339 if options['sudo_password'] && !options['sudo']340 options['sudo'] = true341 Inspec::Log.warn '`--sudo-password` used without `--sudo`. Adding `--sudo`.'342 end343 end344 def finalize_compliance_login(options)345 # check for compliance settings346 # This is always a hash, comes from config file, not CLI opts347 if options.key?('compliance')348 require 'plugins/inspec-compliance/lib/inspec-compliance/api'349 InspecPlugins::Compliance::API.login(options['compliance'])350 end351 end352 class Defaults353 DEFAULTS = {354 exec: {355 'reporter' => ['cli'],356 'show_progress' => false,357 'color' => true,358 'create_lockfile' => true,359 'backend_cache' => true,360 },361 shell: {362 'reporter' => ['cli'],363 },364 }.freeze365 def self.for_command(command_name)366 DEFAULTS[command_name] || {}367 end368 end369 end370end...

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1describe package('nginx') do2 it { should be_installed }3describe service('nginx') do4 it { should be_enabled }5 it { should be_running }6describe port(80) do7 it { should be_listening }8describe command('curl http://localhost') do9 its('stdout') { should match /Hello, world!/ }10describe file('/etc/nginx/sites-enabled/default') do11 it { should_not exist }12describe file('/etc/nginx/sites-available/default') do13 it { should_not exist }14describe file('/etc/nginx/sites-enabled/webserver.conf') do15 it { should exist }16describe file('/etc/nginx/sites-available/webserver.conf') do17 it { should exist }18describe file('/var/www/html/index.html') do19 it { should exist }20describe file('/var/www/html/index.html') do21 its('content') { should match /Hello, world!/ }22describe file('/var/www/html/index.html') do23 its('content') { should match /Hello, world!/ }24describe file('/var/www/html/index.html') do25 its('size') { should > 0 }26describe file('/var/www/html/index.html') do27 it { should be_file }28describe file('/var/www/html/index.html') do29 it { should be_owned_by 'root' }30describe file('/var/www/html/index.html') do31 it { should be_grouped_into 'root' }32describe file('/var/www/html/index.html') do33 it { should be_mode 644 }34describe file('/var/www/html/index.html') do35 it { should be_readable }36describe file('/var/www/html/index.html') do37 it { should be_writable }38describe file('/var/www/html/index.html') do39 it { should be_executable }40describe file('/var/www/html/index.html') do41 its('content') { should match /Hello, world!/ }42describe file('/var/www/html/index.html') do43 its('content') { should match

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 describe file('my_file.txt') do2 it { should exist }3 describe file('my_file.txt') do4 it { should exist }5 describe file('my_file.txt') do6 it { should exist }7 describe file('my_file.txt') do8 it { should exist }9 describe file('my_file.txt') do10 it { should exist }11 describe file('my_file.txt') do12 it { should exist }13 describe file('my_file.txt') do14 it { should exist }15 describe file('my_file.txt') do16 it { should exist }17 describe file('my_file.txt') do18 it { should exist }19 describe file('my_file.txt') do20 it { should exist }21 describe file('my_file.txt') do22 it { should exist }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1describe for_command('ls -l') do2 its('stdout') { should match /total/ }3describe for_script('ls -l') do4 its('stdout') { should match /total/ }5describe for_script('ls -l') do6 its('stdout') { should match /total/ }7describe for_script('ls -l') do8 its('stdout') { should match /total/ }9describe for_script('ls -l') do10 its('stdout') { should match /total/ }11describe for_script('ls -l') do12 its('stdout') { should match /total/ }13describe for_script('ls -l') do14 its('stdout') { should match /total/ }15describe for_script('ls -l') do16 its('stdout') { should match /total/ }17describe for_script('ls -l') do18 its('stdout') { should match /total/ }19describe for_script('ls -l') do20 its('stdout') { should match /total/

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 it { should eq 'redhat' }2 it { should eq '7.4' }3 it { should eq 'x86_64' }4 it { should eq 'centos' }5 it { should eq 'redhat' }6 it { should eq '7.4' }7 it { should eq 'x86_64' }8 it { should eq 'centos' }9 it { should eq 'redhat' }10 it { should eq '7.4' }11 it { should eq 'x86_64' }12 it { should eq 'centos' }13 it { should eq 'redhat' }14 it { should eq '7.4' }15 it { should eq 'x86_64' }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 class Test < Inspec.resource(1)2 class Test2 < Inspec.resource(1)3 class Test3 < Inspec.resource(1)4 class Test4 < Inspec.resource(1)5 class Test5 < Inspec.resource(1)

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1describe command('ls /etc') do2 its('stdout') { should match /passwd/ }3describe command('ls /etc') do4 its('stdout') { should match /passwd/ }5describe command('ls /etc') do6 its('stdout') { should match /passwd/ }7describe command('ls /etc') do8 its('stdout') { should match /passwd/ }9describe command('ls /etc') do10 its('stdout') { should match /passwd/ }11describe command('ls /etc') do12 its('stdout') { should match /passwd/ }13describe command('ls /etc') do14 its('stdout') { should match /passwd/ }15describe command('ls /etc') do16 its('stdout') { should match /passwd/ }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 describe command('echo') do2 it { should exist }3 describe command('echo') do4 it { should exist }5 describe command('echo') do6 it { should exist }7 describe command('echo') do8 it { should exist }9 describe command('echo') do10 it { should exist }11 describe command('echo') do12 it { should exist }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 describe command('ls -l /etc/passwd') do2 its('stdout') { should match /root/ }3 describe command('ls -l /etc/passwd') do4 its('stdout') { should match /root/ }5 describe command('ls -l /etc/passwd') do6 its('stdout') { should match /root/ }7 describe command('ls -l /etc/passwd') do8 its('stdout') { should match /root/ }9 describe command('ls -l /etc/passwd') do10 its('stdout') { should match /root/ }11 describe command('ls -l /etc/passwd') do12 its('stdout') { should match /root/ }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 describe command('ls -l /tmp') do2 its('stdout') { should match /testfile/ }3 describe command('ls -l /tmp') do4 its('stdout') { should_not match /testfile/ }5 describe command('ls -l /tmp') do6 its('stdout') { should match /testfile/ }7 its('stderr') { should eq '' }8 its('exit_status') { should eq 0 }9 describe command('ls -l /tmp') do10 its('stdout') { should match /testfile/ }11 its('stderr') { should eq '' }12 its('exit_status') { should eq 1 }13 it { should eq 'centos' }14 it { should eq 'redhat' }15 it { should eq '7.4' }16 it { should eq 'x86_64' }17 it { should eq 'centos' }18 it { should eq 'redhat' }19 it { should eq '7.4' }20 it { should eq 'x86_64' }21 it { should eq 'centos' }22 it { should eq 'redhat' }23 it { should eq '7.4' }24 it { should eq 'x86_64' }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 class Test < Inspec.resource(1)2 class Test2 < Inspec.resource(1)3 class Test3 < Inspec.resource(1)4 class Test4 < Inspec.resource(1)5 class Test5 < Inspec.resource(1)

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 describe command('ls -l /tmp') do2 its('stdout') { should match /testfile/ }3 describe command('ls -l /tmp') do4 its('stdout') { should_not match /testfile/ }5 describe command('ls -l /tmp') do6 its('stdout') { should match /testfile/ }7 its('stderr') { should eq '' }8 its('exit_status') { should eq 0 }9 describe command('ls -l /tmp') do10 its('stdout') { should match /testfile/ }11 its('stderr') { should eq '' }12 its('exit_status') { should eq 1 }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 describe file('my_file.txt') do2 it { should exist }3 describe file('my_file.txt') do4 it { should exist }5 describe file('my_file.txt') do6 it { should exist }7 describe file('my_file.txt') do8 it { should exist }9 describe file('my_file.txt') do10 it { should exist }11 describe file('my_file.txt') do12 it { should exist }13 describe file('my_file.txt') do14 it { should exist }15 describe file('my_file.txt') do16 it { should exist }17 describe file('my_file.txt') do18 it { should exist }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 describe command('ls -l /tmp') do2 its('stdout') { should match /testfile/ }3 describe command('ls -l /tmp') do4 its('stdout') { should_not match /testfile/ }5 describe command('ls -l /tmp') do6 its('stdout') { should match /testfile/ }7 its('stderr') { should eq '' }8 its('exit_status') { should eq 0 }9 describe command('ls -l /tmp') do10 its('stdout') { should match /testfile/ }11 its('stderr') { should eq '' }12 its('exit_status') { should eq 1 }13 describe file('my_file.txt') do14 it { should exist }15 describe file('my_file.txt') do16 it { should exist }

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 class Test < Inspec.resource(1)2 class Test2 < Inspec.resource(1)3 class Test3 < Inspec.resource(1)4 class Test4 < Inspec.resource(1)5 class Test5 < Inspec.resource(1)

Full Screen

Full Screen

for_command

Using AI Code Generation

copy

Full Screen

1 describe command('ls -l /etc/passwd') do2 its('stdout') { should match /root/ }3 describe command('ls -l /etc/passwd') do4 its('stdout') { should match /root/ }5 describe command('ls -l /etc/passwd') do6 its('stdout') { should match /root/ }7 describe command('ls -l /etc/passwd') do8 its('stdout') { should match /root/ }9 describe command('ls -l /etc/passwd') do10 its('stdout') { should match /root/ }11 describe command('ls -l /etc/passwd') do12 its('stdout') { should match /root/ }

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Inspec_ruby automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful