Script - Reserved Instance Expire
_____
Reserved Instance Expire
_____
Reserved Instance Expire
_____
import boto3
import datetime
from dateutil.tz import tzutc
from botocore.exceptions import ClientError
def handler(event,context):
SENDER = "worxogo.alerts@powerupcloud.com"
#RECIPIENT = ["worxogo.alerts@powerupcloud.com","kanishk@worxogo.com"]
RECIPIENT = ["worxogo.alerts@powerupcloud.com","infra-ops@worxogo.com"]
AWS_REGION = "us-east-1"
SUBJECT = "Reserved Instance Expiry Information"
access_key = "AKIAIVRHBSCHEPQQOHKQ"
secret_key = "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"
client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,
region_name='us-east-1')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
now = datetime.datetime.utcnow().replace(tzinfo=tzutc())
tableHtml=""
counter=0;
for region in ec2_regions:
conn = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,
region_name=region)
reservations = conn.describe_reserved_instances()
for ri in reservations['ReservedInstances']:
if ri['State'] not in ('active', 'payment-pending'):
continue
exp_date=ri['End']
expire_time = ri['Start'] + datetime.timedelta(seconds=ri['Duration'])
if (exp_date - now) < datetime.timedelta(days=7) :
tableHtml=tableHtml+"""<tr><td>"""+ri['ReservedInstancesId']+"""</td><td>"""+ri['InstanceType']+"""</td><td>"""+ri['State']+"""</td><td align="center">"""+str(ri['InstanceCount'])+"""</td><td align="center">"""+str((exp_date - now).days)+"""</td><td align="center">"""+str(exp_date)+"""</td><td>"""+region+"""</tr><tr>"""
counter+=1
if counter > 0:
BODY_HTML = """<html>
<head></head>
<body>
<h1>Reserved Instance Expiry Details</h1>
<p>Please find the expiry details of Reserved Instance below,</p>
<table style="width:100%">
<tr>
<th>Resevation Id</th>
<th>Instance Type</th>
<th>State</th>
<th>Instance Count</th>
<th>Remaining Days</th>
<th>Expiry Date</th>
<th>Region</th>
</tr>"""+tableHtml+"""
</table>
</body>
</html>
"""
CHARSET = "UTF-8"
client = boto3.client('ses',region_name=AWS_REGION)
try:
#Provide the contents of the email.
response = client.send_email(
Destination={
'ToAddresses': RECIPIENT,
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': BODY_HTML,
}
},
'Subject': {
'Charset': CHARSET,
'Data': SUBJECT,
},
},
Source=SENDER
# If you are not using a configuration set, comment or delete the
# following line
)
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
print(response['MessageId'])
Comments
Post a Comment