aws 预留实例到期监控
环境准备
安装python的aws 开发工具包
pip install boto3
配置aws账号
[root@zabbix service]# aws configure
AWS Access Key ID [None]: xxxxxx
AWS Secret Access Key [None]: xxxxx
Default region name [None]:
Default output format [None]:
监控脚本:
#!/usr/bin/env python # -*- coding:utf-8 -*- import boto3,os import datetime from ReservedInstancesMonitor_message import * def reserved_instances_info(): data=response['ReservedInstances'] #send_message="" reserved_instances_number=0 for info in data: #购买时长 purchase_time=info['Duration'] #购买起始时间 purchase_start_time=info['Start'] #print(purchase_time,purchase_start_time) #获取当前时间 current_time=datetime.datetime.now() #print(current_time) #获取过期时间 retired_time=datetime.datetime.strptime( str(purchase_start_time).split('+')[0],"%Y-%m-%d %H:%M:%S.%f") + datetime.timedelta(seconds=purchase_time) #剩余过期时间 retired_left_time=(retired_time -current_time).days if retired_left_time <= 7: #send_message +=info['InstanceType'] +" "+str(info['InstanceCount'])+"\n" reserved_instances_number+=info['InstanceCount'] #print("预留实例类型: " + info['InstanceType']," 过期数量: ",info['InstanceCount'] ," 多少天后过期: " , retired_left_time) return reserved_instances_number if __name__=='__main__': region_list=['ap-northeast-2','eu-central-1'] for region in region_list: print("-"*100) client=boto3.client('ec2',region_name=region) response = client.describe_reserved_instances(Filters=[{'Name':'state','Values':['active',]},]) instances_number=reserved_instances_info() if instances_number != 0: message="【xx告警】区域: " +region+ " " + str(instances_number) +" "+ "台预留实例将于7天后到期,请及时购置!" print (message) send_sms(apikey,message,mobile)
发短信脚本(使用的云片网接口):
#!/usr/bin/python #-*- coding:utf-8 -*- # apikey:成功注册后登录云片官网,进入后台可查看 # text:需要使用已审核通过的模板或者默认模板 # mobile:接收的手机号,仅支持单号码发送 import os import urllib,urllib2,httplib,time from subprocess import Popen,PIPE apikey='xxxx' mobile='xxxx' def send_sms(apikey, text, mobile): #服务地址 sms_host = "sms.yunpian.com" #端口号 port = 443 #版本号 version = "v2" #智能匹配模板短信接口的URI sms_send_uri = "/" + version + "/sms/single_send.json" params = urllib.urlencode({'apikey': apikey, 'text': text, 'mobile':mobile}) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPSConnection(sms_host, port=port, timeout=30) conn.request("POST", sms_send_uri, params, headers) response = conn.getresponse() response_str = response.read() conn.close() return response_str if __name__=='__main__': pass #message="【xx告警】区域: %s %s 台预留实例将于7天后到期,请及时购置!" %(region,instances_number) #print send_message #send_sms(apikey,message,mobile)
云片网配置短信模板
【xx告警】区域: #region# #instance_number# 台预留实例将于7天后到期,请及时购置!
将过期时间调长,测试脚本执行
开启定时任务:
0 2 * * * python /root/monitor/service/ReservedInstancesMonitor.py >>/var/log/aws_reservedinstances.log 2>&1
赠人玫瑰,手有余香,如果我的文章有幸能够帮到你,麻烦帮忙点下右下角的推荐,谢谢!
作者: imcati
出处: https://www.cnblogs.com/imcati/>
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接