Enabling VPC Flow Logs

Length: 00:11:01

Lesson Summary:

VPC flow logs enable you to capture information about the IP traffic going to and from network interfaces in your VPC.

By default, VPC flow logs are not enabled. However, in our scenario, let's say you have a policy that requires they be enabled for any new VPC that gets created in your account.

In this lesson, we will automate the creation of VPC flow logs whenever a new VPC is created.

  • lambda_function.py creates VPC flow logs for the VPC ID in the event.
  • event-pattern.json is the CloudWatch Rule event pattern for monitoring the CreateVpc API call.
  • test-event.json is a sample CloudTrail event that can be used with the Lambda function, as it contains the VPC ID.

Create an IAM Role with Permission to Log to CloudWatch Logs

  1. Allow the VPC Flow Logs service to assume this role:

     aws iam create-role --role-name VPCFlowLogsRole --assume-role-policy-document file://trust-policy.json

    Note the ARN for VPCFlowLogsRole.

    Example: arn:aws:iam::123456789012:role/VPCFlowLogsRole

  2. Grant this role permission to access CloudWatch Logs:

     aws iam put-role-policy --role-name VPCFlowLogsRole --policy-name VPCFlowLogsPolicy --policy-document file://vpc-flow-logs-iam-role.json

Create the Lambda Function

  • Name: EnableVPCFlowLogs
  • Runtime: Python 3.7
  • Role: Create a custom role (use lambda_execution_role.json)
  • Code: lambda_function.py

Create a CloudWatch Event Rule to Trigger Lambda

  1. Select Event Pattern.

    • Service Name: EC2
    • Event Type: AWS API Call via CloudTrail
    • Specific operation(s): CreateVpc
  2. Event Pattern:

         "source": [
         "detail-type": [
             "AWS API Call via CloudTrail"
         "detail": {
             "eventSource": [
             "eventName": [
  3. Click Add target and select the EnableVpcFlowLogs Lambda function.

  4. Click Configure details.

Create a New VPC

  1. Run the following command:

     aws ec2 create-vpc --cidr-block --region us-east-2`
  2. Wait up to a minute for the CloudWatch rule to invoke the Lambda function.

This lesson is only available to Linux Academy members.

Sign Up To View This Lesson

Or Log In

Looking For Team Training?

Learn More