Search code examples
python-3.xamazon-web-servicesboto3amazon-vpcvpc

Boto3: How to check if VPC already exists before creating it


I can create a VPC really quick like this:

import boto3 as boto

inst = boto.Session(profile_name='myprofile').resource('ec2')

def createVpc(nid,az='us-west-2'):
    '''Create the VPC'''
    vpc = inst.create_vpc(CidrBlock = '10.'+str(nid)+'.0.0/16')
    vpc.create_tags(
        Tags = [ { 'Key': 'Name', 'Value': 'VPC-'+nid }, ]
    )
    vpc.wait_until_available()

createVpc('111')

How can I check a VPC with CidrBlock: 10.111.0.0/16 or a Name: VPC-111 already exists before it gets created? I actually wanna do the same check prior to any AWS resource creation but VPC is a start. Best!


EDIT: found that vpcs.filter can be used to query a given VPC tags; e.g.:

fltr = [{'Name':'tag:Name', 'Values':['VPC-'+str(nid)]}]
list(inst.vpcs.filter(Filters=fltr))

which returns a list object like this: [ec2.Vpc(id='vpc-43e56b3b')]. A list with length 0 (zero) is a good indication of a non-existent VPC but was wondering if there is more boto/aws way of detecting that.


Solution

  • Yes you need to use filters with describe_vpcs API.

    The below code will list all VPC's which matches both Name Tag Value and the CIDR block:

    import boto3
    
    client = boto3.client('ec2',region_name='us-east-1')
    response = client.describe_vpcs(
        Filters=[
            {
                'Name': 'tag:Name',
                'Values': [
                    '<Enter you VPC name here>',
                ]
            },
            {
                'Name': 'cidr-block-association.cidr-block',
                'Values': [
                    '10.0.0.0/16', #Enter you cidr block here
                ]
            },        
        ]
    )
    resp = response['Vpcs']
    if resp:
        print(resp)
    else:
        print('No vpcs found')
    

    CIDR block is the primary check for VPC. I would suggest to just use the CIDR Filter alone instead of clubbing with Name Tag as then you can prevent creating VPC with same CIDR Blocks.