stelligent/cfn_nag

Question: custom rules handling Ref!

membra opened this issue · 1 comments

Hi,

I am creating a custom rule that is supposed to prevent starting instances of certain types from launchtemplate

What I have come up so far is this:

# frozen_string_literal: true

require 'cfn-nag/violation'
require_relative 'base'

class F131_LaunchTemplateAllowFamiliesOfEC2Rule < BaseRule
  def rule_text
    'LaunchTemplate - EC2 families should be only of certain families (following changes need to be made t -> t3a, m -> m5, c -> c5, r -> r5)'
  end

  def rule_type
    Violation::FAILING_VIOLATION
  end

  def rule_id
    'F131' # Custom Rule #1
  end

  def audit_impl(cfn_model)
    violating_items = cfn_model.resources_by_type('AWS::EC2::LaunchTemplate').select do |item|
      if item.launchTemplateData.key?("InstanceType")
        item.launchTemplateData['InstanceType'].start_with?('t1', 'm1', 'm2', 'm3', 'c1', 'c3', 'c4', 'm4', 'r3')
      end
    end
    violating_items.map { |item| item.logical_resource_id }
  end
end

What happens is when it is running against a template that has a !Ref in Instance Type like this:

EC2LaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateName: !Sub "${ResourceNameBase}"
      LaunchTemplateData:
        ImageId: !Ref AmiIdParameterStoreLocation
        InstanceType: !Ref InstanceType
        IamInstanceProfile:
          Arn: !GetAtt EC2InstanceProfile.Arn
        Monitoring:

This references this parameter:

  InstanceType:
    Description: WebServer EC2 instance type
    Type: String
    Default: t3a.medium
    AllowedValues:
      - t3a.small
      - t3a.medium
      - m5a.large
      - m5a.xlarge
    ConstraintDescription: must be a valid EC2 instance type.

It throws an error:

/tmp/tmpjhpd6o8h/cfn-nag-rules-main-fcd15c6b9812663222438e0020697e1951b3e854/rules/F131_LaunchTemplateAllowFamiliesOfEC2Rule.rb:22:in `block in audit_impl': undefined method `start_with?' for {"Ref"=>"InstanceType"}:Hash (NoMethodError)\

I was wondering is there a way to handle hashmaps like that in custom rules?

Thanks!

Commenting to follow