python如何获取到预留实例
这篇文章将为大家详细讲解有关python如何获取到预留实例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
boto3是aws提供给python开发者的SDK,我们通过boto3可以获取到预留实例的相关信息。
boto3部署按照方法:
可以参照官方网站https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html。
值得注意的是,因为我们使用zabbix进行监控,所以.aws目录需要在zabbix用户的根目录下创建。
监控脚本:
rinViewer.py:
import datetimeimport jsonimport timeimport sysfrom pytz import timezoneclass rinViewer: def __init__(self,botoclient): self.client = botoclient; self.info = self.client.describe_reserved_instances()["ReservedInstances"]; def simList(self): #return a simple list of reservedinstance and days left. ans = [] for i in self.info: if i["State"] == "active": rins = {"instanceType":i["InstanceType"]} dayleft = self.dayLeft(i["End"]); rins["leftday"] = dayleft; ans.append(rins) return ans; def dayLeft(self,time): #input datetime,return the days left. cst_tz = timezone('Asia/Shanghai'); now = datetime.datetime.now(cst_tz); return (time-now).days; def leftDaysCheck(self,days=30): #if all reinstance left days over 30(default) it will return true,else return false and reason info = self.simList(); for i in info: if i["leftday"] < days: return {"status":False,"reason":i["instanceType"]+" will be expired in "+str(i["leftday"])+"."} return {"status":True}; def typeSum(self,type,count=-1): # return sum of ec2 with the type if count is not set.Or return bool which the sum of ec2 is correct. siminfo = self.simList(); n = 0; for i in siminfo: if i["instanceType"] == type: n = n + 1; if count == -1: return n; elif count == n: return {"status":True} else: return {"status":False,"reason":"Only "+str(n)+" "+type+" reserved instances.Expect "+str(count)} def typeCheck(self,typelist): # return bool that the ec2 reinstances is match the type list or not. for i in typelist: ans = self.typeSum(i["type"],i["sum"]); if ans["status"] == False: return ans; return {"status":True}if __name__ == "__main__": client = boto3.client('ec2'); rinsList=[{"type":"c5.large","sum":2}},{"type":"t2.medium","sum":1},{"type":"m4.large","sum":1}] reqStr = sys.argv[1]; riv = rinViewer(client); if reqStr == "leftdays": if len(sys.argv) > 2: res = riv.leftDaysCheck(int(sys.argv[2]))["status"]; else: res = riv.leftDaysCheck()["status"]; print res; elif reqStr == "typecount": res = riv.typeCheck(rinsList)["status"]; print res;
使用说明
支持两个参数:leftdays和typecount
python rinViewer.py leftdays [days]
会检索你所有的预留实例的到期时间,如果有预留实例到期天数小于days(默认是30),返回false,如果没有临近到期返回true。
python rinViewer.py typecount
在函数中我们定义了rinsList=[{"type":"c5.large","sum":2}},{"type":"t2.medium","sum":1},这里记录了所在region所需要的预留实例数量,当执行时,会比较预留实例数量和rinsList中指定的数量是否存在出入,如果满足了指定的数量则返回true,反之返回false.
当然如果有配置中心,或者其他入口能够获得所需预留实例信息,只要提供给rinViewer.typeCheck对应的list即可。
添加到监控系统:
怎么添加到zabbix,网上文档很多,这里就不介绍了,给个效果图:
关于"python如何获取到预留实例"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。