ECSCreater.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. import json
  4. import uuid
  5. from config_hbgj import Config
  6. from word_generater import decodestr
  7. from aliyunsdkcore.client import AcsClient
  8. from aliyunsdkcore.acs_exception.exceptions import ClientException
  9. from aliyunsdkcore.acs_exception.exceptions import ServerException
  10. from aliyunsdkecs.request.v20140526.CreateInstanceRequest import CreateInstanceRequest
  11. from aliyunsdkecs.request.v20140526.RunInstancesRequest import RunInstancesRequest
  12. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  13. from aliyunsdkecs.request.v20140526.ModifyInstanceChargeTypeRequest import ModifyInstanceChargeTypeRequest
  14. from aliyunsdkecs.request.v20140526.DeleteInstancesRequest import DeleteInstancesRequest
  15. class AliyunECS(object):
  16. # if user=gtgj, only allowed ecs.t5-lc1m1.small for ecs type
  17. # set_DryRun(True) for debug
  18. # rlease instance api ModifyInstanceAutoReleaseTime https://help.aliyun.com/document_detail/47576.html?spm=a2c4g.11186623.6.1191.66777c25Y5tDMN
  19. # request.set_ImageId("m-2ze9rkkcv9k4mi693nob")
  20. # request.set_InstanceType("ecs.t5-lc1m1.small")
  21. # request.set_InstanceName("proxy")
  22. # request.set_InternetChargeType("PayByTraffic")
  23. # request.set_InternetMaxBandwidthOut(1)
  24. # request.set_HostName("porxy")
  25. # request.set_Password("password3324!")
  26. # request.set_SystemDiskSize(40)
  27. # request.set_SystemDiskCategory("cloud_efficiency")
  28. # request.set_Description("proxy")
  29. # request.set_VSwitchId("vsw-2zeay6fvk4kq6dtvyk8nh")
  30. # request.set_InstanceChargeType("PostPaid")
  31. """
  32. {
  33. "InstanceId": "i-2zeat29qpyvlcfh6p17v",
  34. "RequestId": "6D3573AF-B8BC-4679-BA62-F1CBDB25CC7D"
  35. }
  36. """
  37. '''
  38. for choice argments:
  39. InternetChargeType, if instanceChargeType==Prepaid then InternetChargeType=PayByBandwidth else PayByTraffic
  40. InstanceChargeType # if InstanceChargeType==PrePaid then PeriodUnit=Month or InstanceChargeType=PostPaid
  41. InstanceCount
  42. Password
  43. '''
  44. '''static argments:
  45. ImageId
  46. InstanceType
  47. InstanceName
  48. InternetMaxBandwidthOut
  49. HostName
  50. SystemDiskSize
  51. SystemDiskCategory
  52. Description
  53. VSwitchId
  54. '''
  55. # {'RequestId': 'F67D0AE3-8B4A-4A06-88E1-AD037B8D2F3B', 'InstanceIdSets': {'InstanceIdSet': ['i-2ze7anzznp9keos3mzo2', 'i-2ze7anzznp9keos3mzo3']}, 'TradePrice': 53.2}
  56. def __init__(self, user="gtgj", **CreateInfo):
  57. metadata = ["RegionId", "AutoReleaseTime", "InstanceCount"]
  58. self.CreateInfo = CreateInfo
  59. self.set_Region = self.CreateInfo.pop("set_Region")
  60. self.CreateInfo['set_InstanceType'] = "ecs.t5-lc1m1.small"
  61. self.CreateInfo['set_ImageId'] = "m-2ze9rkkcv9k4mi693nob"
  62. self.CreateInfo['set_InstanceName'] = "proxy"
  63. self.CreateInfo['set_InternetMaxBandwidthOut'] = 1
  64. self.CreateInfo['set_HostName'] = "proxy"
  65. self.CreateInfo['set_Description'] = "proxy"
  66. self.CreateInfo['set_SecurityGroupId'] = "sg-2ze4a0k1v1gsidwkez2c"
  67. self.CreateInfo['set_SystemDiskSize'] = 40
  68. self.CreateInfo['set_SystemDiskCategory'] = "cloud_efficiency"
  69. self.CreateInfo['set_VSwitchId'] = "vsw-2zeay6fvk4kq6dtvyk8nh"
  70. # if self.CreateInfo.get("set_InternetChargeType") == "Prepaid" and self.CreateInfo.get("set_InternetChargeType") == "PayByBandwidth" :
  71. if self.CreateInfo.get("set_InstanceChargeType") == "PrePaid":
  72. self.CreateInfo['set_PeriodUnit'] = "Month"
  73. self.CreateInfo['set_Period'] = 1
  74. self.CreateInfo['set_AutoRenewPeriod'] = 1
  75. self.CreateInfo['set_AutoRenew'] = True
  76. self.set_PayType = 1 # 1. PayByBandwidth 2.PayByTraffic
  77. else:
  78. self.PayType = 0
  79. self.client = AcsClient(decodestr(Config.accessKeyId), decodestr(Config.accessSecret), self.set_Region)
  80. @property
  81. def doAaction(self):
  82. self.request.set_accept_format('json')
  83. response = self.client.do_action_with_exception(self.request)
  84. return json.loads(str(response, encoding='utf-8'))
  85. @property
  86. def CreateECSInstance(self):
  87. self.request = RunInstancesRequest()
  88. ecs_password = self.CreateInfo.get("Password")
  89. for k,v in self.CreateInfo.items():
  90. print("""self.request.%s("%s") """ % (k, v))
  91. exec("""self.request.%s("%s") """ % (k, v))
  92. self.request.set_ClientToken(uuid.uuid1())
  93. return self.doAaction
  94. # https://api.aliyun.com/?spm=a2c4g.11186623.2.9.78953290C6BExH#/?product=Ecs&api=DescribeInstances&params={}&tab=DEMO&lang=PYTHON
  95. def DescribeInstances(self, InstanceIds):
  96. self.request = DescribeInstancesRequest()
  97. self.request.set_PageSize(100)
  98. # InstanceIds ["i-2ze551ld3zvhp56r2504"]
  99. self.request.set_InstanceIds(InstanceIds)
  100. Data = self.doAaction
  101. InstancesInfo = []
  102. for instance in Data['Instances']["Instance"]:
  103. PrivateIpAddress = instance['NetworkInterfaces']["NetworkInterface"][0]["PrimaryIpAddress"]
  104. PublicIpAddress = instance["PublicIpAddress"]["IpAddress"][0]
  105. InstanceId = instance["InstanceId"]
  106. InstanceChargeType = instance["InstanceChargeType"]
  107. InstancesInfo.append({'InstanceId':InstanceId, "PublicIpAddress": PublicIpAddress, "PrivateIpAddress":PrivateIpAddress, "InstanceChargeType":InstanceChargeType})
  108. return InstancesInfo
  109. def ReleaseInstances(self, InstanceIds):
  110. InstancesInfo = self.DescribeInstances(InstanceIds)
  111. PrePaidInstanceIds = [instance['InstanceId'] for instance in InstancesInfo if instance['InstanceChargeType'] == "PrePaid"]
  112. if PrePaidInstanceIds:
  113. self.PrePaid2PostPaid(PrePaidInstanceIds)
  114. self.request = DeleteInstancesRequest()
  115. self.request.set_Force(True)
  116. self.request.set_InstanceIds(InstanceIds)
  117. return self.doAaction
  118. def PrePaid2PostPaid(self, InstanceIds):
  119. self.request = ModifyInstanceChargeTypeRequest()
  120. self.request.set_InstanceChargeType("PostPaid")
  121. self.request.set_InstanceIds(InstanceIds)
  122. return self.doAaction
  123. if __name__ == "__main__":
  124. #instance = AliyunECS(set_Region="cn-beijing", set_InternetChargeType="PayByTraffic", set_InstanceChargeType="PostPaid", set_Password="Pass@123!", set_Amount=2)
  125. #instance = AliyunECS(set_Region="cn-beijing", set_InternetChargeType="PayByBandwidth", set_InstanceChargeType="PrePaid", set_Password="Pass@123!", set_Amount=2)
  126. #print(instance.CreateECSInstance)
  127. #instance = AliyunECS(set_Region="cn-beijing")
  128. #print(instance.DescribeInstances(["i-2ze551ld3zvhp56r2504", "i-2ze551ld3zvhp56r250e"]))
  129. instance = AliyunECS(set_Region="cn-beijing")
  130. print(instance.ReleaseInstances(["i-2zefwbdpum6qmsl9yx6x","i-2zefwbdpum6qmsl9yx6y"]))
  131. # def ModifyECSInstance():
  132. #
  133. # def Run():
  134. # self.CreateInfo.get("InstancesCount")