Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: custom rules handling Ref! #591

Open
membra opened this issue Feb 14, 2022 · 1 comment
Open

Question: custom rules handling Ref! #591

membra opened this issue Feb 14, 2022 · 1 comment

Comments

@membra
Copy link

membra commented Feb 14, 2022

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!

@jitterjuice
Copy link

Commenting to follow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants