-
#!/usr/bin/env python
-
# -*- coding: utf-8 -*-
-
#
-
# Date: Jul 25,2016
-
-
'''
-
### Purpose ####
-
-
Correlating the reservations you currently have active with your running instances is a manual, time-consuming, and error prone process.
-
This quick little Python script uses boto3 to inspect your reserved instances and running instances to determine if you currently have any reserved instances which are not being used. Additionally, it will give you a list of non-reserved instances which could benefit from additional reserved instance allocations.
-
-
### prequisite ####
-
-
1. requirement(optional): boto3 and termcolor
-
$ pip install boto3 termcolor (maybe need sudo privilege)
-
-
python >= 2.7
-
-
2. aws credentials configuration
-
See here
-
If you have multiple profiles, you can configure additional, named profiles by using the --profile option.
-
-
$ aws configure --profile pcf-China
-
AWS Access Key ID [None]: xxxxxxxxxxxxxxxxxxxxxxxx
-
AWS Secret Access Key [None]: xxxxxxxxxxxxxxxxxxxxx
-
Default region name [None]: cn-north-1
-
Default output format [None]: text
-
-
##### something else that need your attention !!!!!!
-
-
1. if your Reserved Instance account and Running Instance account are same one, probably you don't need to specify a profile name as below, yet you need to re-write the code under
-
-
the initialization of an instance will be :
-
-
x = Ec2()
-
-
which means a profile name isn't required,it will read from the `default` credentials.
-
-
2. Probably your profile name is different from mine, please modify them on below section
-
-
### aws profile specifications ###
-
-
in this script, my reserve profile is reservation, and running instance profile is pcf-China and concourse.
-
-
'''
-
try:
-
import sys
-
import boto3
-
from termcolor import colored
-
except ImportError:
-
print "either boto3 or termcolor isn't installed, please run \"sudo pip install boto3 termcolor\""
-
sys.exit(1)
-
-
### aws profile specifications ###
-
-
ri_acc_id = ["reservation"]
-
rn_acc_id = ["pcf-China", "concourse"]
-
-
class Ec2 :
-
def __init__(self, profile=None) :
-
self.profile = profile
-
self.session = boto3.session.Session(profile_name = self.profile )
-
self.client = self.session.client("ec2")
-
self.RI = {}
-
self.running_instances = {}
-
-
def Current_ec2_instances(self) :
-
-
for i in self.client.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running','stopped']}])["Reservations"] :
-
tmp = i["Instances"]
-
az_type = tmp[0]["Placement"]["AvailabilityZone"],tmp[0]["InstanceType"]
-
self.running_instances[az_type]=self.running_instances.get(az_type,0) + 1
-
# current ec2 instances, including running/stopped, excluding pending/terminated.
-
#print self.running_instances
-
return self.running_instances
-
-
def RI_ec2(self) :
-
-
target = self.client.describe_reserved_instances()["ReservedInstances"]
-
for i in target :
-
# current reserved ec2 instances, excluding pending-payment | active | payment-failed | retired
-
if i["State"] == "active" :
-
az_type = i["AvailabilityZone"],i["InstanceType"]
-
self.RI[az_type] = i["InstanceCount"]
-
#print self.RI
-
return self.RI
-
-
#####################################################
-
-
-
def do_calc(ri,running) :
-
-
for key in ri :
-
balance = ri[key] - running.get(key,0) # asumme it's zero, if key doesn't appear on RI
-
if balance < 0 :
-
print "%s\t\t%s" %(key,colored(balance,"red"))
-
else :
-
print "%s\t\t%d" %(key,balance)
-
try :
-
del running[key]
-
except Exception,e :
-
pass
-
print "-" * 60
-
print colored("Region\t\tInstanceType\t\treserved-instance-need-to-buy","red")
-
print "-" * 60
-
if running.items() != {}:
-
for k,v in running.items() :
-
print "%s\t\t%d" % (k,v)
-
-
if __name__ == "__main__" :
-
-
### ec2 ###
-
print "#" * 33
-
print "# EC2 statistic #"
-
print "#" * 33
-
# ec2 statistics
-
ri_instance_sum ={}
-
for i in ri_acc_id :
-
reserve_ins = Ec2(i)
-
y = reserve_ins.RI_ec2()
-
# print "### reserved instances details : %s ###" %colored(i,"green")
-
# print "-" * 60
-
#print colored("Region\t\tInstanceType\t\tAmount","green")
-
#print "-" * 60
-
for k,v in y.items():
-
#print "%s\t\t%d" % (k,v)
-
if k not in ri_instance_sum :
-
ri_instance_sum[k] = v
-
else :
-
ri_instance_sum[k] = ri_instance_sum[k] + v
-
-
rn_instance_sum = {}
-
for i in rn_acc_id :
-
x = Ec2(i)
-
#print "\n### running instances details : %s ###" %colored(i,"green")
-
#print "-" * 60
-
#print colored("Region\t\tInstanceType\t\tAmount","green")
-
#print "-" * 60
-
for k,v in x.Current_ec2_instances().items() :
-
-
#print "%s\t\t%d"%(k,v)
-
-
if k not in rn_instance_sum:
-
rn_instance_sum[k] =v
-
else :
-
rn_instance_sum[k] = rn_instance_sum[k] + v
-
-
print "-" * 60
-
print colored("Region\t\tInstanceType\t\tBalance","green")
-
print "-" * 60
-
print colored("\npositive integer means reserved instances remains un-used,while negative integer \nmeans this type of reserved instance is out of capacity, needs to purchase more...","yellow")
-
print "-" * 60
-
-
do_calc(ri_instance_sum,rn_instance_sum)
-
主要是熟悉AWS的Python的boto3。非常的强大,当然也希望官方能给出统计,这样就省得麻烦了。
阅读(1840) | 评论(0) | 转发(0) |