Skip to content

Instantly share code, notes, and snippets.

@btotharye
Last active May 9, 2021 17:09
Show Gist options
  • Save btotharye/83a3f570a3ec9a97958b452452d66e60 to your computer and use it in GitHub Desktop.
Save btotharye/83a3f570a3ec9a97958b452452d66e60 to your computer and use it in GitHub Desktop.
CDK Python VPC with Flow Logs
#!/usr/bin/env python3
from aws_cdk import core
from cdk.cdk_stack import CdkStack
app = core.App()
# Params and stage info
stage = app.node.try_get_context('stage')
props = app.node.try_get_context(stage)
service = app.node.try_get_context('serviceName')
region = app.node.try_get_context('dev')['region']
# Build out stack
CdkStack(app, "{0}-{1}-cdk".format(service, stage), props=props, env={'region': region})
{
"app": "python3 app.py",
"context": {
"serviceName": "vpc-cdk",
"dev": {
"cidr": "10.60.0.0/16",
"vpcAzCount": 1,
"region": "us-east-1"
}
}
}
from aws_cdk import (
core,
aws_ec2 as ec2,
aws_iam as iam,
aws_logs as logs
)
class CdkStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, props, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# VPC Setup
stage = scope.node.try_get_context('stage')
service_name = scope.node.try_get_context('serviceName')
# Setup IAM user for logs
vpc_flow_role = iam.Role(
self, 'FlowLog',
assumed_by=iam.ServicePrincipal('vpc-flow-logs.amazonaws.com')
)
# Create Cloudwatch log group
log_group = logs.LogGroup(
self, 'LogGroup',
log_group_name=service_name,
retention=logs.RetentionDays('ONE_YEAR'),
removal_policy=core.RemovalPolicy('DESTROY')
)
# Setup VPC resource
vpc = ec2.Vpc(
self, '{0}-{1}-vpc'.format(service_name, stage),
cidr=props['cidr'],
max_azs=props['vpcAzCount']
)
# Setup VPC flow logs
vpc_log = ec2.CfnFlowLog(
self, 'FlowLogs',
resource_id=vpc.vpc_id,
resource_type='VPC',
traffic_type='ALL',
deliver_logs_permission_arn=vpc_flow_role.role_arn,
log_destination_type='cloud-watch-logs',
log_group_name=log_group.log_group_name
)
@btotharye
Copy link
Author

Basically just creates a vpc with flow logs and I have it set to destroy so you don't hit errors in the code, eventually I'll set it up to look for a instance of the log group already and just use it.

@jewelsjacobs
Copy link

Nice! Thanks @btotharye 😸

@samuelthan
Copy link

Was pulling my hair on this. Saw your solution, saved my bacon !! thanks @btotharye

@btotharye
Copy link
Author

awesome, I haven't updated some of these in a while been kinda busy will try to eventually

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment