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.