def _terminate_instance(ids): puts("Killing " + ids) if type(ids) == str: ids = ids.split(',') ec2 = _get_conn() ec2.terminate_instances(ids)
def stop_vm(slave): print(colored("DEBUG: DQCCcloud.stop_vm(" + slave.id + ")", 'green')) # stop running instance if DQCCconfig.testmode == True: print(colored("INFO: Testmode - I would run 'ec2.terminate_instances(...)' now.", "yellow")) else: ec2.terminate_instances(instance_ids=[slave.id]) return True
def ec2_terminate(ec2): #filters = {'instance-state-name' : 'running'} reservations = ec2.get_all_instances() instances = [i for r in reservations for i in r.instances] for i in instances: try: print "---Terminating instance: " + i.id ec2.terminate_instances(instance_ids=i.id) except Exception, e: print(e)
def kill_instances(ec2, keyname, min_age, dry_run): now = datetime.utcnow() instances = ec2.get_only_instances(filters={'key-name': keyname}) kill_list = [] for instance in instances: launchtime = datetime.strptime(instance.launch_time, '%Y-%m-%dT%H:%M:%S.%fZ') if (now - launchtime) > min_age: print "Going to kill", instance.id, "launched", instance.launch_time kill_list.append(instance.id) if not dry_run: ec2.terminate_instances(kill_list, dry_run)
def terminateInstance(region,zone,instance_id): """ Terminate an ec2 instance """ try: ec2 = boto.ec2.connect_to_region(region+'-'+zone) ec2.terminate_instances(instance_ids=[instance_id]) return True except Exception as e: logError(e) return False
def terminateInstance(region, zone, instance_id): """ Terminate an ec2 instance """ try: ec2 = boto.ec2.connect_to_region(region + '-' + zone) ec2.terminate_instances(instance_ids=[instance_id]) return True except Exception as e: logError(e) return False
def terminateInstance(): print("Terminating the instance...") try: ec2 = boto.ec2.connect_to_region("ap-south-1", **auth) except Exception as e1: error1 = "Error1: %s" % str(e1) print(error1) sys.exit(0) try: ec2.terminate_instances(instance_ids="") except Exception as e2: error2 = "Error2: %s" % str(e2) print(error2) sys.exit(0)
def changeState(group, instid, action, ec2_inst): # Deprecated # ec2 = boto.connect_ec2() # XXX TODO take region as an option ec2 = boto.vpc.connect_to_region("us-east-1") instancelist = list() # try block this stuff please if group: instances = ec2_inst.find({"group":group},{"_id":1}) for instance in instances: instancelist.append(instance["_id"]) elif instid: instancelist.append(instid) else: print "Internal Error, no instance or group specified" return if action == "stop": reslist = ec2.stop_instances(instance_ids=instancelist) elif action == "start": reslist = ec2.start_instances(instance_ids=instancelist) elif action == "terminate": reslist = ec2.terminate_instances(instance_ids=instancelist) else: print "Internal Error, no action specified" print reslist
def terminate(args, config): instances = args['<instance>'] if instances: ec2 = connection.create(config) for instance in instances: term = ec2.terminate_instances(instance_ids=[instance]) puts(colored.green("Successfully Terminated: %s" % ', '.join( [t.id for t in term])))
def stop_vm_openstack(status_dict): """ Stop vm-s given a dict containing the instance ids Args: status_dict: Dictionary containing information about the instances Returns: None: """ ## terminate the instances instances_to_terminate=[] for i in status_dict.keys(): if status_dict[i] == 'running': instances_to_terminate.append(i.id) print instances_to_terminate try: ec2.terminate_instances(instances_to_terminate) except: print 'Error terminating VMs' return -1 return 0
def terminate_instances(module, ec2, instance_ids): """ Terminates a list of instances module: Ansible module object ec2: authenticated ec2 connection object termination_list: a list of instances to terminate in the form of [ {id: <inst-id>}, ..] Returns a dictionary of instance information about the instances terminated. If the instance to be terminated is running "changed" will be set to False. """ # Whether to wait for termination to complete before returning wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) changed = False instance_dict_array = [] if not isinstance(instance_ids, list) or len(instance_ids) < 1: module.fail_json( msg='instance_ids should be a list of instances, aborting') terminated_instance_ids = [] for res in ec2.get_all_instances(instance_ids): for inst in res.instances: if inst.state == 'running' or inst.state == 'stopped': terminated_instance_ids.append(inst.id) instance_dict_array.append(get_instance_info(inst)) try: ec2.terminate_instances([inst.id]) except EC2ResponseError, e: module.fail_json( msg='Unable to terminate instance {0}, error: {1}'. format(inst.id, e)) changed = True
def terminate_instances(module, ec2, instance_ids): """ Terminates a list of instances module: Ansible module object ec2: authenticated ec2 connection object termination_list: a list of instances to terminate in the form of [ {id: <inst-id>}, ..] Returns a dictionary of instance information about the instances terminated. If the instance to be terminated is running "changed" will be set to False. """ # Whether to wait for termination to complete before returning wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) changed = False instance_dict_array = [] if not isinstance(instance_ids, list) or len(instance_ids) < 1: module.fail_json(msg='instance_ids should be a list of instances, aborting') terminated_instance_ids = [] for res in ec2.get_all_instances(instance_ids): for inst in res.instances: if inst.state == 'running' or inst.state == 'stopped': terminated_instance_ids.append(inst.id) instance_dict_array.append(get_instance_info(inst)) try: ec2.terminate_instances([inst.id]) except EC2ResponseError, e: module.fail_json(msg='Unable to terminate instance {0}, error: {1}'.format(inst.id, e)) changed = True
def terminateInstances(self, instanceId): ec2 = boto.connect_ec2() for account_name in instanceId: print '\tAccount: %s' % account_name d = instanceId[account_name] for region_name in d: print '\t\tRegion: %s' % region_name for instance in d[region_name]: print '\t\t\tAn %s instance: %s' % \ (instance.instance_type, instance.id) print '\t\t\t\tTags=%s' % instance.tags print '\nTerminating instance "%s"' % instance.id ret = ec2.terminate_instances(str(instance.id)) print "Terminated instance %s" % ret
def terminate_instances(region, instance_list): ec2 = boto.ec2.connect_to_region(region) instance_ids = list(map(lambda x: x.id, instance_list)) terminated = ec2.terminate_instances(instance_ids=instance_ids) while True: try_again = False for inst in terminated: inst.update() if inst.state != 'terminated': try_again = True if try_again == True: time.sleep(2) else: break
def stop_node(): start_logging() print(" ".join(argv)) if len(argv) != 2: print("Usage: %s <nodename>" % (argv[0], ), file=sys.stderr) return 1 nodename = argv[1] cc = ClusterConfiguration.from_config() region = get_region() ec2 = boto.ec2.connect_to_region(region) instances = ec2.get_only_instances(filters={"tag:SLURMHostname": nodename}) if len(instances) == 0: print("No instances found for %r" % nodename) return 1 instance_ids = [instance.id for instance in instances] print("Terminating instance(s): %s" % " ".join(instance_ids)) ec2.terminate_instances(instance_ids) return 0
def terminate_machine(instance_id): ec2 = boto.ec2.connect_to_region(settings.aws_region, aws_access_key_id=settings.aws_access, aws_secret_access_key=settings.aws_secret) if not ec2: logging.error('Cannot connect to region %s' % settings.aws_region) return None try: terminated = ec2.terminate_instances([instance_id]) logging.info('Succesfully terminated %d instances' % (len(terminated))) return terminated except Exception, e: logging.exception('Cannot terminate instance %s (%s)' % (instance_id, e)) return None
def stop_node(): start_logging() print(" ".join(argv)) if len(argv) != 2: print("Usage: %s <nodename>" % (argv[0],), file=sys.stderr) return 1 nodename = argv[1] cc = ClusterConfiguration.from_config() region = get_region() ec2 = boto.ec2.connect_to_region(region) instances = ec2.get_only_instances(filters={"tag:SLURMHostname": nodename}) if len(instances) == 0: print("No instances found for %r" % nodename) return 1 instance_ids = [instance.id for instance in instances] print("Terminating instance(s): %s" % " ".join(instance_ids)) ec2.terminate_instances(instance_ids) return 0
def kill_instances(): ids = request.values.getlist("id") ec2 = get_ec2_connection() ec2.terminate_instances(instance_ids=ids) return redirect_with_success("terminated %d instances"%len(ids), "/")
def terminate_instances(location, placement_group='*'): ec2 = boto.ec2.connect_to_region(location) instances = ec2.get_only_instances( filters={"placement-group-name": placement_group}) for inst in instances: ec2.terminate_instances(instance_ids=[inst.id])
from boto.exception import JSONResponseError parser = argparse.ArgumentParser() parser.add_argument('--region', action='store', dest='region') parser.add_argument('--waitsig', action='store', dest='wait') parser.add_argument('--instance', action='store', dest='instance') parser.add_argument('--name', action='store',dest='name') results = parser.parse_args() REGION = results.region WAITURL = results.wait INSTANCE = results.instance NAME = results.name try: rds = boto.rds2.connect_to_region(REGION) ec2 = boto.ec2.connect_to_region(REGION) #create rds subnet and option group - enabling Mirroring to allow for MultiAZ MSSQL Deployments # rds_option_group = rds.create_option_group(NAME, "sqlserver-se", "11.00", option_group_description="MSSQL Option Group with Mirroring") rds.modify_option_group(option_group_name=NAME, options_to_include=[{'Mirroring'}],apply_immediately=True) except JSONResponseError, e: print str(e.body['Error']['Message']) payload = { 'Status' : 'FAILURE' ,'Reason' : str(e.body['Error']['Message']), 'UniqueId' : 'ModifyOptionGrp' , 'Data' : str(e.body['Error']['Message']) } r = requests.put(WAITURL, data=json.dumps(payload), headers={"Content-Type" : ""}, verify=True) sys.exit(1) payload = { 'Status' : 'SUCCESS' ,'Reason' : 'Option Group Modified', 'UniqueId' : 'ModifyOptionGrp' , 'Data' : 'Success' } r = requests.put(WAITURL, data=json.dumps(payload), headers={"Content-Type" : ""}, verify=True) ec2.terminate_instances(INSTANCE) sys.exit(0)
def terminate_instances(module, ec2, instance_ids): """ Terminates a list of instances module: Ansible module object ec2: authenticated ec2 connection object termination_list: a list of instances to terminate in the form of [ {id: <inst-id>}, ..] Returns a dictionary of instance information about the instances terminated. If the instance to be terminated is running "changed" will be set to False. """ # Whether to wait for termination to complete before returning wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) changed = False instance_dict_array = [] if not isinstance(instance_ids, list) or len(instance_ids) < 1: module.fail_json( msg='instance_ids should be a list of instances, aborting') terminated_instance_ids = [] for res in ec2.get_all_instances(instance_ids): for inst in res.instances: if inst.state == 'running' or inst.state == 'stopped': terminated_instance_ids.append(inst.id) instance_dict_array.append(get_instance_info(inst)) try: ec2.terminate_instances([inst.id]) except EC2ResponseError as e: module.fail_json( msg='Unable to terminate instance {0}, error: {1}'. format(inst.id, e)) changed = True # wait here until the instances are 'terminated' if wait: num_terminated = 0 wait_timeout = time.time() + wait_timeout while wait_timeout > time.time() and num_terminated < len( terminated_instance_ids): response = ec2.get_all_instances( \ instance_ids=terminated_instance_ids, \ filters={'instance-state-name':'terminated'}) try: num_terminated = sum([len(res.instances) for res in response]) except Exception as e: # got a bad response of some sort, possibly due to # stale/cached data. Wait a second and then try again time.sleep(1) continue if num_terminated < len(terminated_instance_ids): time.sleep(5) # waiting took too long if wait_timeout < time.time() and num_terminated < len( terminated_instance_ids): module.fail_json( msg="wait for instance termination timeout on %s" % time.asctime()) #Lets get the current state of the instances after terminating - issue600 instance_dict_array = [] for res in ec2.get_all_instances(instance_ids=terminated_instance_ids,\ filters={'instance-state-name':'terminated'}): for inst in res.instances: instance_dict_array.append(get_instance_info(inst)) return (changed, instance_dict_array, terminated_instance_ids)
def terminate_compute(instance_ids): ec2.terminate_instances(instance_ids)
key_name='<key_name>', instance_type='t2.micro', security_groups=['<security-group-name>']) instance = reservations.instances[0] while instance.state != 'running': time.sleep(5) instance.update() ec2.create_tags([instance.id], {'Name': instance_name}) return instance.public_dns_name except Exception, e3: error3 = "Error3: %s" % str(e3) return error3 # to terminate an instance with given instance_id (i-......) def terminateInstance(input_id): print "Terminating instance" try: ec2 = boto.ec2.connect_to_region("us-west-2", **auth) except Exception, e1: error4 = "Error4: %s" % str(e1) return error4 try: ec2.terminate_instances(instance_ids=input_id) return "successfully terminated instance" except Exception, e2: error5 = "Error5: %s" % str(e2) return error5
def terminate_instance(instance_id): global print_only if not print_only: ec2.terminate_instances([instance_id]) return
#!/usr/bin/env python import boto.ec2 ec2 = boto.ec2.connect_to_region('ap-northeast-1') t = ec2.get_all_instances() for i in t: print i.instances for k in i.instances: print k.id ec2.terminate_instances(k.id)
def terminate_instance(choice): print 'Terminating instance: ', choice ec2.terminate_instances(instance_ids=choice) check_state(choice)
#!/usr/bin/env python import boto.ec2 aws_access_key = 'xxxx' aws_secret_key = 'xxxx' region = 'ap-northeast-1' ec2 = boto.ec2.connect_to_region(region, aws_access_key_id= aws_access_key, aws_secret_access_key =aws_secret_key) t = ec2.get_all_instances() for i in t: print i.instances for k in i.instances: print k.id ec2.terminate_instances(k.id)
message = 'Finished baking AMI {image_id} for {environment} {deployment} {play}.'.format( image_id=ami, environment=args.environment, deployment=args.deployment, play=args.play) send_hipchat_message(message) except Exception as e: message = 'An error occurred building AMI for {environment} ' \ '{deployment} {play}. The Exception was {exception}'.format( environment=args.environment, deployment=args.deployment, play=args.play, exception=repr(e)) send_hipchat_message(message) error_in_abbey_run = True finally: print if not args.no_cleanup and not args.noop: if sqs_queue: print "Cleaning up - Removing SQS queue - {}".format(run_id) sqs.delete_queue(sqs_queue) if instance_id: print "Cleaning up - Terminating instance ID - {}".format( instance_id) # Check to make sure we have an instance id. if instance_id: ec2.terminate_instances(instance_ids=[instance_id]) if error_in_abbey_run: exit(1)
instance = create_box() subprocess.check_output(['cp', key_filename, os.path.join(os.path.dirname(key_filename), 'ec2-{}.pem'.format(instance.ip_address))]) public_dns_name = instance.public_dns_name ip_address = instance.ip_address test_ssh(instance, key_filename) ssh_command = 'ssh -i {key} ubuntu@{ip} "'.format(ip=ip_address, key=key_filename) mosh_command = 'mosh ubuntu@{ip} --ssh="ssh -i {key}"'.format(ip=ip_address, key=key_filename) if 'quitafterec2spinup' in sys.argv: print(ssh_command) quit() try: print(ssh_command) apt_installs() print(mosh_command) fix_sshd_config() except Exception: print("{} failed!".format(public_dns_name)) if not os.environ.get('MEMEX_IP_ADDR'): ec2.terminate_instances([instance.id]) raise try: create_vagrant() install_miniconda() install_repo(public_dns_name, ip_address) run_salt() except Exception: print(ssh_command) print(mosh_command) raise
if args.noop: print "Would have created sqs_queue with id: {}\nec2_args:".format( run_id) pprint(ec2_args) ami = "ami-00000" else: run_summary, ami = launch_and_configure(ec2_args) print print "Summary:\n" for run in run_summary: print "{:<30} {:0>2.0f}:{:0>5.2f}".format( run[0], run[1] / 60, run[1] % 60) print "AMI: {}".format(ami) if args.mongo_uri: mongo_con.update_ami(ami) mongo_con.update_deployment(ami) finally: print if not args.no_cleanup and not args.noop: if sqs_queue: print "Cleaning up - Removing SQS queue - {}".format(run_id) sqs.delete_queue(sqs_queue) if instance_id: print "Cleaning up - Terminating instance ID - {}".format( instance_id) # Check to make sure we have an instance id. if instance_id: ec2.terminate_instances(instance_ids=[instance_id])
def ec2_terminate(): ec2 = conn_region ec2.terminate_instances(instance_ids=[instances]) print "Success"