These are just bash and python scripts that I wrote to do AWS chores conveniently.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
3.0 KiB

#!/usr/bin/env python3
# Scan all VPCs for Internet Gateways that are not attached
# Delete them
import urllib3
import sys
import boto3
import botocore
import argparse
session = None
debug = False
class initArgs(object):
def __init__(self):
self.parser = argparse.ArgumentParser()
"--no-verify-ssl", action='store_true', help="Disable SSL verification.")
"--profile", type=str, help="The credential profile used to execute this job. This configuration is not required if 'aws configure' has been run and a [default] profile is defined in ~/aws/crednetial", required=False)
self.parser.add_argument( "--debug", action='store_true', help="don't actually do anything")
self.args = self.parser.parse_args(sys.argv[1:])
def get_args(self):
return self.args
def getRegions():
client = session.client('ec2', verify=False)
except botocore.exceptions.NoRegionError as e:
print("Error initiating AWS client!")
print("Have you configured your AWS region? (e.g. in ~/aws/config) See 'aws configure' ")
print("If you are using a specific profile, use --profile")
regions = []
for region in client.describe_regions()['Regions']:
# print(region['RegionName'])
return regions
except botocore.exceptions.ClientError as e:
print("Error executing AWS commands!")
print("Have you configured your AWS credentials? (e.g. in ~/aws/crednetial) See 'aws configure' ")
print("Or perhaps the access token has expired?")
def detach_internet_gateways(vpcId, client):
igws = client.describe_internet_gateways( )
for igw in igws['InternetGateways']:
igwId = igw['InternetGatewayId']
if( len(igw['Attachments']) == 0 ):
if not debug:
client.delete_internet_gateway( InternetGatewayId=igwId )
print("actually ", end="")
print("wanted to ", end="")
print("delete Internet Gateway " + igwId + " from " + vpcId + "...")
def scan_vpcs(regions):
client = None
count = 0
for region in regions:
client = session.client( 'ec2', verify=False, region_name=region )
response = client.describe_vpcs( )
print("[{}]: {} VPCs".format(region, len(response['Vpcs'])))
if( len(response['Vpcs']) > 0 ):
for vpcs in response['Vpcs']:
vpcId = vpcs['VpcId']
detach_internet_gateways(vpcId, client)
count += 1
return count
if __name__ == "__main__":
args = initArgs().get_args()
if( args.debug == True ):
debug = True
session = boto3.Session(profile_name=args.profile)
print("Scanning all VPCs in all regions...\n")
count = scan_vpcs(getRegions())
print("{} VPCs scanned.".format(count))