code-dumps/aws/AwsEnvReview.py

94 lines
3.0 KiB
Python
Executable File

#!/usr/bin/python3
import boto3
import jmespath
import re
from pprint import pprint
from datetime import date
def printTitle(title):
print("=" * 20)
print(title)
print("=" * 20)
return
def printSubTitle(title):
print(title)
return
def getAllRegions(myclient):
return jmespath.search("Regions[*].RegionName", myclient.describe_regions(AllRegions=False))
def getAgeFromDate(inputDate):
today = date.today()
delta = today - inputDate.date()
return delta.days
sts = boto3.client("sts")
aid = sts.get_caller_identity().get("Account")
printTitle("Ec2 service review")
printSubTitle("[Cost saving] Instances stopped for over 14 days - Consider backing up instances and terminate them")
client = boto3.client('ec2')
regions = getAllRegions(client)
print("Region", "AccountID", "InstanceId", "DaysStopped", sep=",")
for r in regions:
client = boto3.client('ec2', region_name=r)
response = client.describe_instances()
if len(response.get("Reservations")) > 0:
for i in jmespath.search("Reservations[*].Instances[*]", response):
if i[0].get("State").get("Name") == "stopped":
print(r, aid, i[0].get("InstanceId"), getAgeFromDate(i[0].get("UsageOperationUpdateTime")), sep=",")
printSubTitle("[Performance] Previous instance generation - Consider using current instance generation")
client = boto3.client('ec2')
regions = getAllRegions(client)
print("Region", "AccountID", "InstanceId", "InstanceType", sep=",")
for r in regions:
client = boto3.client('ec2', region_name=r)
response = client.describe_instances()
if len(response.get("Reservations")) > 0:
for i in jmespath.search("Reservations[*].Instances[*]", response):
if re.search("^(t1|t2|m3|m1|m2|m4|c1|c2|c3|c4|r3|r4|i2)", i[0].get("InstanceType")) is not None:
print(r, aid, i[0].get("InstanceId"), i[0].get("InstanceType"), sep=",")
printSubTitle("[Cost saving] Unattached EBS volumes - Consider taking snapshot and delete volumes")
print("Region", "AccountID", "VolumeId", "Size", "VolumeType", sep=",")
for r in regions:
client = boto3.client('ec2', region_name=r)
response = client.describe_volumes(
Filters=[
{
'Name': 'status',
'Values': ['available']
}
]
)
for i in response.get("Volumes"):
print(r, aid, i.get("VolumeId"), i.get("Size"), i.get("VolumeType"), sep=",")
printSubTitle("[Security] Unencrypted EBS volumes - Consider replacing volume with encrypted ones")
print("Region", "AccountID", "VolumeId", "Size", "VolumeType", sep=",")
for r in regions:
client = boto3.client('ec2', region_name=r)
response = client.describe_volumes(
Filters=[
{
'Name': 'encrypted',
'Values': ['false']
},
{
'Name': 'status',
'Values': ['in-use']
}
]
)
for i in response.get("Volumes"):
print(r, aid, i.get("VolumeId"), i.get("Size"), i.get("VolumeType"), sep=",")