This project will use AWS Config to run organization defined custom rules to check for resource to be in compliance via Lambda functions.
Steps:
- Create Two EC2 instances.
 - Create Lambda function
 - Create Config Rule
 - Monitor for non-compliant resources
 
1. Create 2 EC2 resources.
-- create an instance with Monitoring Enabled.
-- create an instance with Monitoring Disabled.
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
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.
Credits:
Thanks to Abhishek Veeramalla 


    
Top comments (0)