This page looks best with JavaScript enabled

AWS Boto3: Using Boto3 to Describe VPC

 ·  ☕ 2 min read  ·  ✍️ Brett Johnson

To describe a VPC is to retrieve the values of it attributes. A task we might perform to validate configuration.

This article will demonstrate the following:

  • Find VPC ID using filters
  • Retrieve VPC configuration values

Information on Boto3 can be found here.

This post assumes that you already have a working Boto3 installation. Including IAM configuration to perform the task. If you have not, click here for the install document.

Modules and EC2 connection

We require the JSON and Boto3 modules. Thus, they will be imported at the start of the script. The reason for Boto3 should be fairly straight forward. To make the responses readable, JSON is required.

The third line connects to EC2 for our region. Adjust the region name as required.

1
2
3
4
import json
import boto3
ec2 = boto3.resource('ec2', region_name='ap-southeast-2')
client = boto3.client('ec2')

Retrieving VPCs

Filters are used to scope our results. These filters are based on tags. Such as, Name, VPCID etc. You can use multiple entries for the value or a wildcard “*”.

1
filters = [{'Name':'tag:Name', 'Values':['VPN*']}]

<

1
filters = [{'Name':'tag:Name', 'Values':['VPN01', 'VPN02']}]

Now to perform the query using the ec2.vpcs resource.

<

1
vpcs = list(ec2.vpcs.filter(Filters=filters))

The variable vpcs now contains a list of VPCIDs for the VPCs which matched our filter.

<

1
[ec2.Vpc(id='vpc-1b7e'), ec2.Vpc(id='vpc-dcb7')]

Describing the VPCs

We have searched for VPCs and their IDs are now in the list vpcs. It’;s now time to see some information on them.

We will utilise a for loop to achieve this.

1
2
3
4
5
6
7
for vpc in vpcs:
    response = client.describe_vpcs(
        VpcIds=[
            vpc.id,
        ]
    )
    print(json.dumps(response, sort_keys=True, indent=4))

vpc.id provides the ID number for each entry.

I have ended this with a print. You can of course change that to store the output for further use.

The formatted response should be similar to this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
    "ResponseMetadata": {
        "HTTPStatusCode": 200,
        "RequestId": "5bed6fab-fc86"
    },
    "Vpcs": [
        {
            "CidrBlock": "192.168.0.0/25",
            "DhcpOptionsId": "dopt-8",
            "InstanceTenancy": "default",
            "IsDefault": false,
            "State": "available",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "VPN1"
                }
            ],
            "VpcId": "vpc-1b7e"
        }
    ]
}

Summary

The script provides a framework to audit VPCs and their configurations. I hope that you found it helpful.

The script in full can be found at https://github.com/oversizedspoon/DescribeVPC-BOTO3

Share on

Brett Johnson
WRITTEN BY
Brett Johnson
Automator of things