-
-
Save jewelsjacobs/08d9e65709289fea60be8850d01b505f to your computer and use it in GitHub Desktop.
CDK Python VPC with Flow Logs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"app": "python3 app.py", | |
"context": { | |
"serviceName": "vpc-cdk", | |
"dev": { | |
"cidr": "10.60.0.0/16", | |
"vpcAzCount": 1, | |
"region": "us-east-1" | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment