Inspec include_controls or require_controls based on regex

205 Views Asked by At

Is there a way to include controls of a 'depends' profile based on a regex? And if not, is there a way to include all controls, and overwrite impact with fixed value on all controls?

Code should look something like this, where 'controlname' is the variable that is required to be determined somehow:

include_controls 'depends-profile' do
  if controlname.match(/some regex/)    
     control *controlname*
     impact 1.0
  end
end

Goal is to prevent having to add all controls individually.

A bit digging delivered me this:

   include_controls 'dependent-profile' do
      list_of_controls = @conf['profile'].runner_context.rules.keys
      list_of_controls.map { |path| path.gsub(@conf['profile'].profile_name+'/','') }
      list_of_controls.each do |controlname|
          if controlname.match(/some regex/)
             control controlname do        # include and overwrite impact
                impact 0.1
             end
          end
          if controlname.match(/some other regex/)
             control controlname           # just include
          end
      end
   end

Any ideas how to accomplish this in a neat and future proof way?

1

There are 1 best solutions below

0
On

A solution might look like:

include_controls '<dependent-profile>' do

  # Scan through all the controls we pulled in
  profile_context.all_controls.each do |c|

    # Grab the control name from control c
    handled_control_name = c.instance_variable_get(:@__rule_id)

    # If it matches the regex 
    if handled_control_name =~ /<myRegex>/

      # Overwrite the impact and tags
      control handled_control_name do
        impact 'critical'
        tag 'myTag'
      end

    end
  end
end