server_decomission.py 2.97 KB
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author tiexin.yang@yoho.cn

from qcloud.qcloud_api import QcloudApi
from zabbix import delete_host_by_ip
import datetime
import argparse
import os,shutil
import sys
import time
import json
import re


"""
  作用:通过制定ip销毁,退还按需/按量付费类型实例,同时注销zabbix host
  依赖:zabbix.py(注销zabbix host)
  Demo:
        python server_decomission.py 1.2.3.4
"""


class consoleRobot(object):
    def __init__(self,secretId='',secretKey=''):
        if not secretId or not secretKey:
            self.secretId,self.secretKey = open('/home/ansible/.qcloud_config').read().strip('\n').split('\n')
        else:
            self.secretId,self.secretKey = secretId,secretKey

        self.receivers = ['tiexin.yang@yoho.cn','chunhua.zhang@yoho.cn']
        self.client = QcloudApi(self.secretId,self.secretKey)


    def LocateInstanceByIp(self,privateIp):
        params = {
            "Action": "DescribeInstances",
            "Filters.0.Name": "private-ip-address",
            "Filters.0.Values.0": privateIp
        }
        result = self.client.do_query(params,"cvm.ap-beijing.tencentcloudapi.com/",api_version=3)
        instances = result["Response"]["InstanceSet"]
        if len(instances) == 0:
            print "查询结果为空,请确认输入IP无误后再试"
            return False
        else:
            instance = instances[0]
            instanceId,instanceName = instance["InstanceId"],instance["InstanceName"]
            return instanceId,instanceName

    def ReturnInstanceById(self,instanceId):
        params = {
            "Action":"TerminateInstances",
            "InstanceIds.0":instanceId
            }
        result = self.client.do_query(params,"cvm.ap-beijing.tencentcloudapi.com",api_version=3)
        return result

    def ReturnInstanceByIp(self,privateIp):
        print '查询IP对应的实例ID'
        result = self.LocateInstanceByIp(privateIp)
        if result:
            instanceId,instanceName = result
            print u'即将退还实例...请确认如下信息无误:\n\t实例ID:{0}\n\t实例IP:{1}\n\t实例名称:{2}'.format(instanceId,privateIp,instanceName)
            feedBack = str(raw_input('确认?(Y/N): ')).upper()
            if feedBack == 'Y':
                print '开始退还实例...{0}'.format(instanceId)
                rsp = self.ReturnInstanceById(instanceId)['Response']
                if rsp.has_key('Error'):
                    print json.dumps(rsp['Error'],indent=4)
                    print '实例退还失败'
                    return 1
                else:
                    print '实例退还成功!'
                    print '开始注销zabbix host...'
                    delete_host_by_ip(privateIp)
                    return 0
            else:
                print '任务取消'
                return 0
        else:
            return 0
    
if __name__ == '__main__':
    demo = consoleRobot()
    demo.ReturnInstanceByIp(sys.argv[1])