Fetching VPC details using AWS Lambda

Vinayak Pandey
2 min readJun 30, 2020

Often in an Enterprise environment, it’s important to have visibility about VPCs and associated components like NACLs, Route Tables etc. This sort of details can be very useful while performing operations like updating Route Tables or NACLs.

For this demo, we have 2 VPCs in North Virginia region. .

Each VPC has a Public and a Private subnet.Private VPC in VPC_US_EAST_1 VPC doesn’t have a NAT gateway or NAT instance associated with it while Private VPC in VPC2_US_EAST_1 VPC has a NAT gateway attached. Each subnet has a different Route Table associated with it.

We have few instances running in and each subnet(4 in our case) has at least 1 running instance.

We also need SES setup in order to send our VPC report via mail. You may also need to whitelist the recipient’s email address/addresses via SES console.

Before creating our Lambda function, create an IAM role for that Lambda with following IAM permissions:

“ec2:DescribeInstances”,
“ec2:DescribeVpcs”,
“ses:SendRawEmail”,
“ec2:DescribeSubnets”,
“ec2:DescribeNetworkAcls”,
“ec2:DescribeRouteTables”

Now create Lambda function with Python3.7 runtime and associate the role we just created, with this function.

Now copy lambda code from https://raw.githubusercontent.com/vinycoolguy2015/awslambda/master/netwwork_report.py

You can set Lambda timeout to 5 minutes. This function requires 2 environment variables:

Key: sender Value: email address used to send mail(domain listed in SES like info@yourorganization.com)

Key: receiver Value: recipient’s email address(need to whitelist in SES)

Now we are ready. You can run this function on a regular basis using CloudWatch Rules or just on add hoc basis. Once the function executes successfully, recipient will receive mail with a csv attached containing following details:

Region, VPCId, VPCCidr, VPCName, SubnetId, SubnetCidr, SubnetAZ, SubnetName, AvailableIPs, RouteTableId, RouteTableName, GatewayId, NACLId, InstanceCount, Instances Name

--

--