Best Inspec_ruby code snippet using Inspec.resources
generate.rb
Source:generate.rb
...8module InspecPlugins::Tfkit::Terraform9 class Generate10 # parse through the JSON and generate InSpec controls11 def self.parse_generate(tf_file, resource_path, platform)12 # parse the tfstate file to get the Terraform resources13 tfstate = InspecPlugins::Tfkit::FileHelper.parse_json(tf_file)14 absolutename = File.absolute_path(tf_file)15 # take those Terraform resources and map to InSpec resources by name and keep all attributes16 # resources -> [{name1 -> {unfiltered_attributes}, name2 -> {unfiltered_attributes}]17 parsed_resources = parse_resources(tfstate, resource_path, platform)18 # InSpec controls generated from matched_resources and attributes19 generated_controls = parse_controls(parsed_resources, absolutename, platform)20 # Inspec::Log.debug "tfkit::Terraform::Generate.parse_generate generated_controls = #{generated_controls}"21 generated_controls22 end23 # returns the list of all InSpec resources found in the tfstate file24 def self.parse_resources(tfstate, resource_path, _platform)25 # iterate over the resources26 @resources = {}27 tf_resources = tfstate['resources'] || tfstate['planned_values']['root_module']['resources']28 tf_resources.each do |tf_res|29 resource_type = tf_res['type']30 if resource_type.match('^random_(id|uuid|string)')31 Inspec::Log.debug "tfkit::Terraform.Generate.parse_generate resource_type = #{resource_type} SKIPPED"32 next33 end # this is a Terraform resource, not a provider resource34 # load resource pack resources35 if resource_path36 InspecPlugins::Tfkit::InspecHelper.load_resource_pack(resource_path)37 end38 # add translation layer39 if InspecPlugins::Tfkit::InspecHelper::TRANSLATED_RESOURCES.key?(resource_type)40 Inspec::Log.debug "tfkit::Terraform::Generate.parse_resources resource_type = #{resource_type} #{InspecPlugins::Tfkit::InspecHelper::TRANSLATED_RESOURCES[resource_type]} TRANSLATED"41 resource_type = InspecPlugins::Tfkit::InspecHelper::TRANSLATED_RESOURCES[resource_type]42 end43 @resources[resource_type] = {} if @resources[resource_type].nil?44 # does this match an InSpec resource?45 if InspecPlugins::Tfkit::InspecHelper.available_resources.include?(resource_type)46 Inspec::Log.debug "tfkit::Terraform::Generate.parse_resources resource_type = #{resource_type} MATCHED"47 if tfstate['planned_values']48 parse_planfile(tf_res, resource_type)49 else50 parse_statefile(tf_res, resource_type)51 end52 else53 # Inspec::Log.debug InspecPlugins::Tfkit::InspecHelper.available_resources54 Inspec::Log.debug "tfkit::Terraform.Generate.parse_generate resource_type = #{resource_type} SKIPPED"55 end56 end57 @resources58 end59 # take the resources and map to describes60 def self.parse_controls(resources, absolutename, platform) # rubocop:disable Metrics/AbcSize61 controls = []62 # iterate over the resources types and their ids63 resources.keys.each do |resource_type|64 # Inspec::Log.debug "Tfkit::Terraform::Generate.parse_controls: ResourceType: #{JSON.pretty_generate(resources[resource_type])}"65 66 resources[resource_type].keys.each do |resource_id|67 # Inspec::Log.debug "Tfkit::Terraform::Generate.parse_controls: #{resource_type}::#{resource_id}"68 # insert new control based off the resource's ID69 ctrl = Inspec::Control.new70 ctrl.id = "#{resource_type}::#{resource_id}"71 ctrl.title = "inspec-tfkit #{resource_type}::#{resource_id}"72 ctrl.descriptions[:default] = "#{resource_type}::#{resource_id} from the source file #{absolutename}\nGenerated by inspec-tfkit v#{InspecPlugins::Tfkit::VERSION}"73 ctrl.impact = '1.0'74 describe = Inspec::Describe.new75 case platform # this may need to get refactored away once Azure is tested76 when 'aws'77 qualifier = [resource_type, {}]78 if InspecPlugins::Tfkit::InspecHelper.available_resource_qualifiers(platform).key?(resource_type) # there are additional qualifiers79 first = true80 InspecPlugins::Tfkit::InspecHelper.available_resource_qualifiers(platform)[resource_type].each do |parameter|81 Inspec::Log.debug "tfkit::Terraform::Generate.parse_controls #{resource_type} qualifier found = #{parameter} MATCHED"82 if first # this is the id for the resource83 value = resources[resource_type][resource_id]['id'] # pull value out of the tf attributes84 first = false85 else86 value = resources[resource_type][resource_id][parameter.to_s] # pull value out of the tf attributes87 end88 qualifier[1][parameter] = value89 end90 end91 describe.qualifier.push(qualifier)92 when 'azure'93 # this is a hack for azure, we need a better longterm solution94 # if resource.start_with?('azure_')95 # name = resource_id.split('/').last96 # else97 # name = resource_id98 # end99 # if resource_type.start_with?('azure_')100 # if resource_type.eql?('azure_resource_group')101 # describe.qualifier.push([resource_type, name: name])102 # else103 # resource_group = resource_id.split('resourceGroups/').last.split('/').first104 # describe.qualifier.push([resource_type, name: name, group_name: resource_group])105 # end106 # Hack for plan files only107 qualifier = [resource_type, {} ]108 resource_group = resources[resource_type][resource_id]['resource_group_name']109 name = resources[resource_type][resource_id]['name']110 describe.qualifier.push([resource_type, name: name, resource_group: resource_group])111 when 'gcp'112 qualifier = [resource_type, {}]113 if InspecPlugins::Tfkit::InspecHelper.available_resource_qualifiers(platform).key?(resource_type)114 InspecPlugins::Tfkit::InspecHelper.available_resource_qualifiers(platform)[resource_type].each do |parameter|115 Inspec::Log.debug "tfkit::Terraform::Generate.parse_controls #{resource_type} qualifier found = #{parameter} MATCHED"116 value = resources[resource_type][resource_id][parameter.to_s] # pull value out of the tf attributes117 qualifier[1][parameter] = value118 end119 end120 describe.qualifier.push(qualifier)121 end122 # ensure the resource exists unless Azure, which currently doesn't support it as of InSpec 2.2123 # unless resource_type.start_with?('azure_')124 describe.add_test(nil, 'exist', nil)125 # end126 # if there's a match, see if there are matching InSpec properties127 inspec_properties = InspecPlugins::Tfkit::InspecHelper.resource_properties(resource_type, platform)128 # push stuff back into inspec_properties?129 resources[resource_type][resource_id].keys.each do |attr|130 if inspec_properties.member?(attr)131 Inspec::Log.debug "tfkit::Terraform::Generate.parse_controls #{resource_type} inspec_property = #{attr} MATCHED"132 value = resources[resource_type][resource_id][attr]133 if value134 # check to see if there is a translate for this attr135 property = InspecPlugins::Tfkit::InspecHelper.translated_resource_property(platform, resource_type, attr)136 describe.add_test(property, 'cmp', value)137 else138 Inspec::Log.debug "tfkit::Terraform::Generate.parse_controls #{resource_type} inspec_property = #{attr} SKIPPED FOR NIL"139 end140 else141 Inspec::Log.debug "tfkit::Terraform::Generate.parse_controls #{resource_type} inspec_property = #{attr} SKIPPED"142 end143 end144 ctrl.add_test(describe)145 controls.push(ctrl)146 end147 end148 # Inspec::Log.debug "tfkit::Terraform::Generate.parse_generate controls = #{controls}"149 controls150 end151 def self.parse_planfile(planfile, resource_type)152 Inspec::Log.debug 'tfkit::Terraform::Generate.parse_planfile called'153 resource_id = planfile['address']154 resource_attributes = planfile['values']155 @resources[resource_type][resource_id] = resource_attributes156 end157 def self.parse_statefile(statefile, resource_type)158 Inspec::Log.debug 'tfkit::Terraform::Generate.parse_statefile called'159 statefile['instances'].each do |instance|160 resource_id = instance["attributes"]['id']161 resource_attributes = instance['attributes']162 # Inspec::Log.debug "tfkit::Terraform::Generate.parse_statefile: @resources[#{resource_type}][#{resource_id}] = #{resource_attributes}"163 @resources[resource_type][resource_id] = resource_attributes 164 end165 end166 end167end...
Rakefile
Source:Rakefile
...75 system('cd inspec ; git pull')76 else77 system('git clone https://github.com/inspec/inspec')78 end79 resources_content = {}80 puts 'generate_inspec_snippets :: Processing resources'81 Dir.glob('inspec/docs-chef-io/content/inspec/resources/*.md').sort.each do |doc_file|82 doc_file_content = File.read(doc_file)83 doc_file_name = doc_file.split('/').last.split('.').first84 # Skip any docs that start with "_" (such as _index)85 next if doc_file_name =~ /^\_.*/86 resource_description = doc_file_content.match(/Use the.*/)87 # Grab the first syntax example from the Markdown file88 resource_example = doc_file_content.match(/(describe.*[\s\S]*?end)$/)[0].gsub("\n ", "\n\t").gsub("\n end", "\nend")89 # Build the snippet for this resource90 resource_output_content = {91 'prefix' => doc_file_name,92 'body' => resource_example,93 'description' => resource_description,94 'scope' => 'source.ruby.chef_inspec',95 }96 # Save the parsed resource to the resources_content hash to be written later97 resources_content[doc_file_name] = resource_output_content98 end99 file_content = JSON.pretty_generate(resources_content)100 puts 'generate_inspec_snippets :: Saving Updates to ../snippets/chef_inspec_resources.json'101 File.write('../snippets/chef_inspec_resources.json', file_content)102end...
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...
resources
Using AI Code Generation
1describe file('/etc/passwd') do2 it { should exist }3 it { should be_file }4 it { should be_owned_by 'root' }5 its('mode') { should cmp '0644' }6describe service('sshd') do7 it { should be_installed }8 it { should be_enabled }9 it { should be_running }10describe package('httpd') do11 it { should be_installed }12describe command('ls -l /etc') do13 its('stdout') { should match /passwd/ }14 its('exit_status') { should eq 0 }15describe file('/etc/passwd') do16 it { should exist }17 it { should be_file }18 it { should be_owned_by 'root' }19 its('mode') { should cmp '0644' }20describe service('sshd') do21 it { should be_installed }22 it { should be_enabled }23 it { should be_running }24describe package('httpd') do25 it { should be_installed }26describe command('ls -l /etc') do27 its('stdout') { should match /passwd/ }28 its('exit_status') { should eq 0 }29describe file('/etc/passwd') do30 it { should exist }31 it { should
resources
Using AI Code Generation
1describe file('/etc/passwd') do2 it { should exist }3describe file('/etc/shadow') do4 it { should exist }5describe file('/etc/group') do6 it { should exist }7describe file('/etc/gshadow') do8 it { should exist }9describe file('/etc/hosts') do10 it { should exist }11describe file('/etc/hosts.allow') do12 it { should exist }13describe file('/etc/hosts.deny') do14 it { should exist }15describe file('/etc/hostname') do16 it { should exist }17describe file('/etc/resolv.conf') do18 it { should exist }19describe file('/etc/nsswitch.conf') do20 it { should exist }21describe file('/etc/sysconfig/network') do22 it { should exist }23describe file('/etc/sysconfig/network-scripts') do24 it { should exist }25describe file('/etc/sys
resources
Using AI Code Generation
1 its('names') { should include 'file' }2 its('names') { should include 'service' }3 its('names') { should include 'file' }4 its('names') { should include 'service' }5 its('names') { should include 'file' }6 its('names') { should include 'service' }7 its('names') { should include 'file' }8 its('names') { should include 'service' }9 its('names') { should include 'file' }10 its('names') { should include 'service' }11 its('names') { should include 'file' }12 its('names') { should include 'service' }13 its('names') { should include 'file' }14 its('names') { should include 'service' }15 its('names') { should include 'file' }16 its('names') { should include 'service' }17 its('names') { should include 'file' }
resources
Using AI Code Generation
1 describe file('/tmp/1.txt') do2 it { should exist }3 describe file('/tmp/2.txt') do4 it { should exist }5 describe file('/tmp/3.txt') do6 it { should exist }7 describe file('/tmp/4.txt') do8 it { should exist }9 describe file('/tmp/5.txt') do10 it { should exist }11 describe file('/tmp/6.txt') do12 it { should exist }13 describe file('/tmp/7.txt') do14 it { should exist }15 describe file('/tmp/8.txt') do16 it { should exist }17 describe file('/tmp/9.txt') do18 it { should exist }
resources
Using AI Code Generation
1describe file('/tmp/1.txt') do2 it { should exist }3 its('mode') { should cmp '0644' }4 its('size') { should cmp 0 }5describe file('/tmp/2.txt') do6 it { should exist }7 its('mode') { should cmp '0644' }8 its('size') { should cmp 0 }9describe file('/tmp/3.txt') do10 it { should exist }11 its('mode') { should cmp '0644' }12 its('size') { should cmp 0 }13describe file('/tmp/1.txt') do14 it { should exist }15 its('mode') { should cmp '0644' }16 its('size') { should cmp 0 }17describe file('/tmp/2.txt') do18 it { should exist }19 its('mode') { should cmp '0644' }20 its('size') { should cmp 0 }21describe file('/tmp/3.txt') do22 it { should exist }23 its('mode') { should cmp '0644' }24 its('size') { should cmp 0 }25describe file('/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt') do26 it { should exist }27 its('mode') { should cmp '0644' }28 its('size') { should cmp 0 }29describe file('/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt') do30 it { should exist }31 its('mode') { should cmp '0644' }32 its('size') { should cmp 0 }33describe file('/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt') do34 it { should exist }35 its('mode')
resources
Using AI Code Generation
1 files = inspec.resources('file')2 expect(files).not_to be_empty3 files = inspec.resources('file')4 expect(files).not_to be_empty5 files = inspec.resources('file')
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!!