DEV Community

Jasper Rodda
Jasper Rodda

Posted on • Edited on

AWS Config: Run Org rules to check Resource compliance via Lambda functions.

This project will use AWS Config to run organization defined custom rules to check for resource to be in compliance via Lambda functions.

Steps:

  1. Create Two EC2 instances.
  2. Create Lambda function
  3. Create Config Rule
  4. Monitor for non-compliant resources

1. Create 2 EC2 resources.

-- create an instance with Monitoring Enabled.
-- create an instance with Monitoring Disabled.
Enter fullscreen mode Exit fullscreen mode

Image description

2. Create Lambda function.

Note: Configure lambda to trigger timeout for 10 secs (Lambda, Config tab, timeout)

import boto3
import json

def lambda_handler(event, context):

    # Get the specific EC2 instance.
    ec2_client = boto3.client('ec2')

    # Assume compliant by default
    compliance_status = "COMPLIANT"  

    # Extract the configuration item from the invokingEvent
    config = json.loads(event['invokingEvent'])

    configuration_item = config["configurationItem"]

    # Extract the instanceId
    instance_id = configuration_item['configuration']['instanceId']

    # Get complete Instance details
    instance = ec2_client.describe_instances(InstanceIds=[instance_id])['Reservations'][0]['Instances'][0]

    # Check if the specific EC2 instance has Cloud Trail logging enabled.

    if not instance['Monitoring']['State'] == "enabled":
        compliance_status = "NON_COMPLIANT"

    evaluation = {
        'ComplianceResourceType': 'AWS::EC2::Instance',
        'ComplianceResourceId': instance_id,
        'ComplianceType': compliance_status,
        'Annotation': 'Detailed monitoring is not enabled.',
        'OrderingTimestamp': config['notificationCreationTime']
    }

    config_client = boto3.client('config')

    response = config_client.put_evaluations(
        Evaluations=[evaluation],
        ResultToken=event['resultToken']
    )  

    return response

Enter fullscreen mode Exit fullscreen mode

3. Create Config Rule

  • AWS Config --> Rule --> Add rule --> Custom Lambda Rule
  • Give the Following details
  • Name : rule-ec2-compliance A unique name for the rule.
  • Description - optional Describe what the rule evaluates and how to fix resources that don't comply.
  • AWS Lambda function ARN: arn:aws:lambda:us-east-1:9879879878665:function:rule-ec2-compliance
  • Evaluation mode : When configuration changes
  • Click Next and Save Rule.

4. Monitor resources based on rules.

Image description

Credits:
Thanks to Abhishek Veeramalla

Top comments (0)