def delete_after_pay_instance(ip): instance_id = get_instance_id_by_ip(ip) check_instance_stopped(instance_id) request = DeleteInstanceRequest() request.set_InstanceId(instance_id) _send_request(request) logging.info("instance %s delete task submit successfully.", instance_id)
def test_server_error_with_a_bad_json(self): from aliyunsdkecs.request.v20140526.DeleteInstanceRequest import DeleteInstanceRequest from aliyunsdkcore.vendored.six.moves import http_client request = DeleteInstanceRequest() request.set_InstanceId("blah") client = self.init_client() # test invalid json format def implementation_of_do_action(request): return 400, {}, b"bad-json" client.implementation_of_do_action = implementation_of_do_action try: client.do_action_with_exception(request) assert False except ServerException as e: self.assertEqual("SDK.UnknownServerError", e.get_error_code()) # self.assertEqual("ServerResponseBody: 'bad-json'", e.get_error_msg()) self.assertEqual("ServerResponseBody: bad-json", e.get_error_msg()) # test valid json format but no Code or Message def implementation_of_do_action(request): return 400, {}, b"""{"key" : "this is a valid json string"}""" client.implementation_of_do_action = implementation_of_do_action try: client.do_action_with_exception(request) assert False except ServerException as e: self.assertEqual("SDK.UnknownServerError", e.get_error_code()) self.assertEqual( """ServerResponseBody: {"key" : "this is a valid json string"}""", e.get_error_msg()) # test missing Code in response def implementation_of_do_action(request): return 400, {}, b"{\"Message\": \"Some message\"}" client.implementation_of_do_action = implementation_of_do_action try: client.do_action_with_exception(request) assert False except ServerException as e: self.assertEqual("SDK.UnknownServerError", e.get_error_code()) self.assertEqual("""Some message""", e.get_error_msg()) # test missing Code in response def implementation_of_do_action(request): return 400, {}, b"{\"Code\": \"YouMessedSomethingUp\"}" client.implementation_of_do_action = implementation_of_do_action try: client.do_action_with_exception(request) assert False except ServerException as e: self.assertEqual("YouMessedSomethingUp", e.get_error_code()) self.assertEqual( """ServerResponseBody: {"Code": "YouMessedSomethingUp"}""", e.get_error_msg())
def delete_instance(self, instance_id): status = self.get_instance_status_by_id(instance_id) if status != ECS_STATUS_STOPPED: logger.warning("instance [%s] is not in [%s],current status [%s], cannot delete it", instance_id, ",".join([ECS_STATUS_STOPPED]), status) return None request = DeleteInstanceRequest() request.set_InstanceId(instance_id) response = self.execute(request) return response
def test_server_error_normal(self): from aliyunsdkecs.request.v20140526.DeleteInstanceRequest import DeleteInstanceRequest request = DeleteInstanceRequest() request.set_InstanceId("blah") try: response = self.client.do_action_with_exception(request) assert False except ServerException as e: self.assertEqual("InvalidInstanceId.NotFound", e.get_error_code()) self.assertEqual("The specified InstanceId does not exist.", e.get_error_msg())
def releaseInstance(client, instance_id): request = DeleteInstanceRequest() request.set_accept_format('json') request.set_InstanceId(instance_id) request.set_Force(True) response = client.do_action_with_exception(request) return response
def stop_instance(self, ecsId): request = DeleteInstanceRequest() request.set_accept_format('json') request.set_InstanceId(ecsId) request.set_Force(True) body = self.client.do_action_with_exception(request) print("Successful deleted.")
def stop_and_delete(self, instance_id): """ :argument instance_id :return: """ request = StopInstanceRequest() request.set_accept_format('json') request.set_InstanceId(instance_id) try: response = self.client.do_action_with_exception(request) logging.info("Start to stop Ecs : %s" % instance_id) if ResponseUtil.success(response): logging.info("Start to delete Ecs : %s" % instance_id) time.sleep(60) request = DeleteInstanceRequest() request.set_accept_format('json') request.set_InstanceId(instance_id) response = self.client.do_action_with_exception(request) if ResponseUtil.success(response): return True, None return False, str(response, encoding='utf-8') return False, str(response, encoding='utf-8') except Exception as e: logging.error("Failed to delete ecs, cause by exception : ", e) return False, e
def delete(instance_id): request = DeleteInstanceRequest() request.set_accept_format("json") request.set_InstanceId(instance_id) request.set_Force(True) response = client.do_action_with_exception(request) return json.loads(response)
def _terminate_instance(self): """Terminate the instance.""" client = self._connect() request = DeleteInstanceRequest() request.set_accept_format('json') request.set_Force(True) request.set_InstanceId(self.running_instance_id) client.do_action_with_exception(request)
def deleteMachine(self): clt = self.createECS_Client() # 必须先停止 ecs,才可以删除 request = StopInstanceRequest() request.set_InstanceId(self.instanceID) logger.debug("stop instance: " + self.instanceID) for retry in range(0, MAX_RETRY): resp = self._send_request(clt, request) if resp['code'] != 0 and resp['msg'][ 'Code'] != 'IncorrectInstanceStatus': logger.warn("stop instance failed, due to: " + str(resp)) continue else: break logger.debug("resp: " + str(resp)) if resp['code'] != 0 and resp['msg'][ 'Code'] != 'IncorrectInstanceStatus': return resp request = DeleteInstanceRequest() request.set_InstanceId(self.instanceID) logger.debug("delete instance: " + self.instanceID) while True: resp = self._send_request(clt, request) if resp['code'] == 0: logger.debug("delete instance OK, return %s" % resp['msg']) break logger.debug("response code: %s", str(response['code'])) if resp['code'] != 'IncorrectInstanceStatus': logger.error("delete instance failed with %s" % resp['msg']) ret['code'] = 1 ret['msg'] = "delete instance failed with" + str(resp['msg']) return ret logger.warn("delete instance failed with IncorrectInstanceStatus") time.sleep(1) logger.debug("delete instance done.") """删除 EIP request = UnassociateEipAddressRequest() request.set_InstanceId(self.instanceID) request.set_AllocationId(self.assoID) """ ret = {} ret['code'] = 0 ret['msg'] = "delete machine succ" ret['Hostname'] = self.instanceID ret['InstanceID'] = self.instanceID ret['InnerAddress'] = "" ret['EipAddress'] = "" ret['LockReason'] = "" ret['ExpiredTime'] = "" return ret
def deleteInstance(InstanceId): request = DeleteInstanceRequest() request.set_accept_format('json') request.set_InstanceId(InstanceId) response = client.do_action_with_exception(request) response = json.loads(str(response, encoding='utf-8')) return response
def delete_instance(self, instance_id, retry=True): status = self.get_instance_status_by_id(instance_id) if status != ECS_STATUS_STOPPED: logger.error( "instance [%s] is not in [%s],current status [%s], cannot delete it", instance_id, ",".join([ECS_STATUS_STOPPED]), status) return None # somethings even it's already ECS_STATUS_STOPPED, we still can not delete it. # just sleep 10 seconds # we can also retry several times time.sleep(10) try_times = 5 while try_times > 0: try: if not retry: try_times = 0 request = DeleteInstanceRequest() request.set_InstanceId(instance_id) request.set_Force(True) response = self.execute(request) logger.info("successfully delete instance [%s]", instance_id) return response except Exception as e: try_times -= 1 time.sleep(5) logger.exception("cannot delete instance [%s],retry", instance_id)
def delete_instance(self, instance_id): """ Release a pay-as-you-go instance or an expired subscription instance. :param instance_id: The ID of the instance that you want to release. """ request = DeleteInstanceRequest() request.set_InstanceId(instance_id) request.set_Force(True) logging.info("Delete %s command submit successfully", instance_id) self._send_request(request)
def main(): dat = getIntanceID() print(dat) # print(list(dat.keys())) if dat: instanceID = list(dat.keys())[0] kid,ksec = getkey.getKeys() client = AcsClient(kid, ksec, 'cn-zhangjiakou') request = DeleteInstanceRequest() request.set_accept_format('json') request.set_InstanceId(instanceID) request.set_Force(True) response = client.do_action_with_exception(request) # python2: print(response) print(str(response, encoding='utf-8')) rdic = json.loads(response) if 'RequestId' in rdic: os.remove(fileName) else: print('not heave instance!')
def free(): instance_list = acdb.db.load_or("instance_list", []) region_instance_id_list = [[e["RegionId"], e["InstanceId"]] for e in instance_list] # Stop ECS instance for (region_id, instance_id) in region_instance_id_list: client = AcsClient( conf.secret["aliyun"]["access_key"], conf.secret["aliyun"]["access_secret"], region_id, ) req = StopInstanceRequest() req.set_accept_format("json") req.set_InstanceId(instance_id) client.do_action_with_exception(req) print("Stop", region_id, instance_id) print("Wait") for _ in range(1 << 32): if sum([ e["Status"] == "Stopped" for e in info(region_instance_id_list) ]) == len(region_instance_id_list): break time.sleep(30) # Delete ECS instance for (region_id, instance_id) in region_instance_id_list: client = AcsClient( conf.secret["aliyun"]["access_key"], conf.secret["aliyun"]["access_secret"], region_id, ) req = DeleteInstanceRequest() req.set_accept_format("json") req.set_InstanceId(instance_id) client.do_action_with_exception(req) print("Delete", instance_id) acdb.db.save("instance_list", [])
############################################################### # ECS Insatanceの停止 from aliyunsdkecs.request.v20140526.StopInstanceRequest import StopInstanceRequest request = StopInstanceRequest() request.set_accept_format('json') request.set_InstanceId(INSTANCE_ID) response = client.do_action_with_exception(request) print(str(response, encoding='utf-8')) # ECS Insatanceの削除 from aliyunsdkecs.request.v20140526.DeleteInstanceRequest import DeleteInstanceRequest request = DeleteInstanceRequest() request.set_accept_format('json') request.set_InstanceId(INSTANCE_ID) response = client.do_action_with_exception(request) print(str(response, encoding='utf-8')) # Security Groupの削除 from aliyunsdkecs.request.v20140526.DeleteSecurityGroupRequest import DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest() request.set_accept_format('json') request.set_SecurityGroupId(SECURITY_GROUP_ID) response = client.do_action_with_exception(request) print(str(response, encoding='utf-8'))
def _delete_vm(self, id): request = DeleteInstanceRequest() request.set_InstanceId(id) request.set_Force(True) response = self._send_request(request)
def delete(self): request = DeleteInstanceRequest() request.set_InstanceId(self.instance_id) _do_request(self._client, request, {})