Amazon Web Services (AWS) - List Virtual Private Cloud (VPC) using Python boto3

by
Jeremy Canfield |
Updated: April 29 2024
| Amazon Web Services (AWS) articles
This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using Python boto3. If not, check out my article Python (Scripting) - Getting Started with Amazon Web Services (AWS) boto3.
Here is the minimal boilerplate code without any error handling to list your Virtual Private Clouds (VPCs).
#!/usr/bin/python3
import boto3
client = boto3.client('ec2')
response = client.describe_vpcs()
print(response)
Here is a more practical example, with try/except/else error handling.
#!/usr/bin/python3
import boto3
import sys
try:
client = boto3.client('ec2')
except Exception as exception:
print(exception)
sys.exit(1)
try:
response = client.describe_vpcs()
except Exception as exception:
print(exception)
else:
for vpc in response['Vpcs']:
print(vpc)
Something like this should be returned.
{
'CidrBlock': '10.0.0.0/24',
'DhcpOptionsId': 'dopt-017f0a715e4ce2fc9',
'State': 'available',
'VpcId': 'vpc-0a9d4cb29e2748444',
'OwnerId': '123456789012',
'InstanceTenancy': 'default',
'CidrBlockAssociationSet': [
{
'AssociationId': 'vpc-cidr-assoc-07bcabb27322c8281',
'CidrBlock': '10.0.0.0/24',
'CidrBlockState': {
'State': 'associated'
}
},
{
'AssociationId': 'vpc-cidr-assoc-0113cedd8171ec855',
'CidrBlock': '10.31.0.0/16',
'CidrBlockState': {
'State': 'associated'
}
}
],
'IsDefault': False,
'Tags': [
{
'Key': 'Name',
'Value': 'my-vpc'
}
]
}
Did you find this article helpful?
If so, consider buying me a coffee over at