A Config rule that checks that all EC2 instances are of the type specified.

 
Items
4
Size
5.1 KB
Missing Parameters
AWSTemplateFormatVersion: '2010-09-09'
Resources:
  CustomConfigRule:
    Type: 'AWS::Config::ConfigRule'
    Properties:
      ConfigRuleName: ec2_desired_instance_type
      Description: >-
        A Config rule that checks that all EC2 instances are of the type
        specified.
      InputParameters:
        desiredInstanceType: ''
      Scope:
        ComplianceResourceTypes:
          - 'AWS::EC2::Instance'
      Source:
        Owner: CUSTOM_LAMBDA
        SourceIdentifier:
          'Fn::GetAtt':
            - LambdaFunction
            - Arn
        SourceDetails:
          - EventSource: aws.config
            MessageType: ConfigurationItemChangeNotification
          - EventSource: aws.config
            MessageType: OversizedConfigurationItemChangeNotification
    DependsOn: LambdaInvokePermissions
  LambdaInvokePermissions:
    Type: 'AWS::Lambda::Permission'
    Properties:
      FunctionName:
        'Fn::GetAtt':
          - LambdaFunction
          - Arn
      Action: 'lambda:InvokeFunction'
      Principal: config.amazonaws.com
  LambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      FunctionName: LambdaForec2_desired_instance_type
      Handler: index.lambda_handler
      Role:
        'Fn::GetAtt':
          - LambdaIamRole
          - Arn
      Runtime: python3.6
      Code:
        ZipFile:
          'Fn::Join':
            - |+

            - - ''
              - '#'
              - >-
                # This file made available under CC0 1.0 Universal
                (https://creativecommons.org/publicdomain/zero/1.0/legalcode)
              - '#'
              - '# Ensure all EC2 Instances are of a Given Type'
              - >-
                # Description: Checks that all EC2 instances are of the type
                specified
              - '#'
              - '# Trigger Type: Change Triggered'
              - '# Scope of Changes: EC2:Instance'
              - '# Required Parameter: desiredInstanceType'
              - '# Example Value: t2.small'
              - '# '
              - >-
                # See https://aws.amazon.com/ec2/instance-types/ for more
                instance types
              - ''
              - import boto3
              - import json
              - ''
              - 'def is_applicable(config_item, event):'
              - '    status = config_item[''configurationItemStatus'']'
              - '    event_left_scope = event[''eventLeftScope'']'
              - '    test = ((status in [''OK'', ''ResourceDiscovered'']) and'
              - '            event_left_scope == False)'
              - '    return test'
              - ''
              - ''
              - 'def evaluate_compliance(config_item, rule_parameters):'
              - '    if (config_item[''resourceType''] != ''AWS::EC2::Instance''):'
              - '        return ''NOT_APPLICABLE'''
              - ''
              - '    elif (config_item[''configuration''][''instanceType''] =='
              - '            rule_parameters[''desiredInstanceType'']):'
              - '        return ''COMPLIANT'''
              - '    else:'
              - '        return ''NON_COMPLIANT'''
              - ''
              - ''
              - 'def lambda_handler(event, context):'
              - '    invoking_event = json.loads(event[''invokingEvent''])'
              - '    rule_parameters = json.loads(event[''ruleParameters''])'
              - ''
              - '    compliance_value = ''NOT_APPLICABLE'''
              - ''
              - '    if is_applicable(invoking_event[''configurationItem''], event):'
              - '        compliance_value = evaluate_compliance('
              - '                invoking_event[''configurationItem''], rule_parameters)'
              - ''
              - '    config = boto3.client(''config'')'
              - '    response = config.put_evaluations('
              - '       Evaluations=['
              - '           {'
              - '               ''ComplianceResourceType'': invoking_event[''configurationItem''][''resourceType''],'
              - '               ''ComplianceResourceId'': invoking_event[''configurationItem''][''resourceId''],'
              - '               ''ComplianceType'': compliance_value,'
              - '               ''OrderingTimestamp'': invoking_event[''configurationItem''][''configurationItemCaptureTime'']'
              - '           },'
              - '       ],'
              - '       ResultToken=event[''resultToken''])'
              - ''
      Timeout: 300
    DependsOn: LambdaIamRole
  LambdaIamRole:
    Type: 'AWS::IAM::Role'
    Properties:
      RoleName: IAMRoleForec2_desired_instance_type
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess'
        - 'arn:aws:iam::aws:policy/service-role/AWSConfigRulesExecutionRole'
        - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
      Policies: []
Parameters: {}
Metadata: {}
Conditions: {}

Customize Cf Template

Rule Parameters

 
* Required field
Additional Attributes
Lambda Code (Python)