Exemplo n.º 1
0
def SwitchInstance(InstanceID, Action):
	if (Action == 'stop'):
	    print "Stoping Instance", InstanceID 
	    ec2.stop_instances(InstanceID)
	elif (Action == 'start'):
	    print "Starting Instance", InstanceID 
	    ec2.start_instances(InstanceID)
Exemplo n.º 2
0
def f_stop(ec2, vpc, objects):
    # Create list of objects to print
    instance_list, instance_print, vpn_list, vpn_print = c_object_list(objects)

    if instance_print:
        # Stop instance
        print('Instance Stopping Process >>>')
        instances = ec2.get_all_instances()
        for inst in instances:
            if inst.instances[0].id in instance_list or len(instance_list[0]) == 0:
                if inst.instances[0].state == 'running':
                    ec2.stop_instances(instance_ids=inst.instances[0].id)
                    print('ID: ' + inst.instances[0].id + ' has been stopped.')
                elif inst.instances[0].state == 'stopped':
                    print('ID: ' + inst.instances[0].id + ' is already stopped.')
                else:
                    print('ID: ' + inst.instances[0].id + ' is under the ' + inst.instances[0].state + ' state.')

    if vpn_print:
        # Print vpn information
        print('\n' + 'Vpn Stopping Process >>>')
        vpns = vpc.get_all_vpn_connections()
        for v in vpns:
            if v.state == 'available':
                vpc.delete_vpn_connection(v.id, dry_run=False)
                print('ID: ' + v.id + ' has been deleted.')
            elif v.state == 'deleted':
                print('ID: ' + v.id + ' is already deleted.')
            else:
                print('ID: ' + v.id + ' is under the ' + v.state + ' state.')

    return
Exemplo n.º 3
0
def stopInstance(ec2Id):
    print "Stopping instance..."
    ec2 = boto.ec2.connect_to_region(region, aws_access_key_id=accessKeyId, aws_secret_access_key=accessKeySecret)
    ec2.stop_instances(instance_ids=ec2Id)
    print('Instance Id : ' + ec2Id)
    print('Command processed...')
    time.sleep(10)
    print('Instance Status : ' + statusInstance(ec2Id))
Exemplo n.º 4
0
def stopInstance():
    print("Stopping the instance...")
    try:
        ec2 = boto.ec2.connect_to_region("us-west-2", **auth)
    except:
        sys.exit(0)
    try:
        ec2.stop_instances(instance_ids=instance_id)
    except:
        sys.exit(0)
Exemplo n.º 5
0
def ec2_instance_ops(operation, name=None, hostname=None):
    data = {}
    try:
        region = bottle.request.query.region
        account = bottle.request.query.account

        if not region:
            raise ValueError("Region not selected")

        if not account:
            raise ValueError("Account not selected")

        with closing(ec2_open_conn(region, account)) as ec2:
            machines = ec2_instance_list(ec2, account, name)
            if machines:
                if operation == "list":
                    data = {
                        "result": "ok",
                        "machine": machines,
                        "total": len(machines)
                    }
                elif operation == "start":
                    ec2.start_instances(instance_ids=[name])
                    # if hostname:
                    #     r53_manage(hostname,
                    #                machines[0]["network"]["public_ip"],
                    #                "CREATE")
                    data = {
                        "result": "ok",
                        "message": "Instance {} started".format(name)
                    }
                elif operation == "stop":
                    ec2.stop_instances(instance_ids=[name])
                    # if hostname:
                    #     r53_manage(hostname,
                    #                machines[0]["network"]["public_ip"],
                    #                "DELETE")
                    data = {
                        "result": "ok",
                        "message": "Instance {} stopped".format(name)
                    }
                elif operation == "reboot":
                    ec2.reboot_instances(instance_ids=[name])
                    data = {
                        "result": "ok",
                        "message": "Instance {} rebooted".format(name)
                    }
            else:
                raise bottle.HTTPError(status=500, body="No managed machines")

    except ValueError as err:
        raise bottle.HTTPError(status=500, body=str(err))

    return data
Exemplo n.º 6
0
def stopInstance(id1, ec2):
    print "Stopping the instance..."
    #ec2 = boto.ec2.connect_to_region("us-east-2", **auth)

    try:
        print "inst.id", id1
        ec2.stop_instances(instance_ids=id1)

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)
Exemplo n.º 7
0
def stop_instances(ec2, to_stop=None):
  """Ensure instances are stopped

  Args:
    ec2: boto ec2 object
    to_stop: list, instances to stop
  """
  if to_stop:
    logger.info('Stopping instances: %s' % to_stop)

    if not DRY_RUN:
      ec2.stop_instances(to_stop)
  else:
    logger.debug('Nothing to stop')
Exemplo n.º 8
0
def stop_instances(ec2, to_stop=None):
  """Ensure instances are stopped

  Args:
    ec2: boto ec2 object
    to_stop: list, instances to stop
  """
  if to_stop:
    logger.info('Stopping instances: %s' % to_stop)

    if not DRY_RUN:
      ec2.stop_instances(to_stop)
  else:
    logger.debug('Nothing to stop')
Exemplo n.º 9
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
Exemplo n.º 10
0
def stopInstance():
    print("Stopping the instance...")

    try:
        ec2 = boto.ec2.connect_to_region("us-east-1", **auth, security_token=os.environ.get('AWS_SESSION_TOKEN', None))

    except Exception as e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
         ec2.stop_instances(instance_ids="i-078f12dd0854c092e")

    except Exception as e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)
Exemplo n.º 11
0
def stopInstance():
    print("Stopping the instance...")
    try:
        ec2 = boto.ec2.connect_to_region("eu-central-1",** auth)

    except Exception as e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
        ec2.stop_instances(instance_ids="i-06fc2d09c9b6bace4")

    except Exception as e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)
    print(".......................")
    print("Stopped the instance...")
Exemplo n.º 12
0
def check():
    # Get all reservations.
    reservations = ec2.get_all_instances(args['<instance_id>'])

    # Get current day + hour (using GMT)
    hh  = int(time.strftime("%H", time.gmtime()))
    day = time.strftime("%a", time.gmtime()).lower()

    started = []
    stopped = []

    # Loop reservations/instances.
    for r in reservations:
        for instance in r.instances:
            logger.info("Evaluating instance \"%s\"", instance.id)

            try:
                data     = instance.tags[config.get('schedule','tag','schedule')]
                schedule = json.loads(data)

                try:
                    if hh == schedule[day]['start'] and not instance.state == 'running':
                        logger.info("Starting instance \"%s\"." %(instance.id))
                        started.append(instance.id)
                        ec2.start_instances(instance_ids=[instance.id])
                except:
                    pass # catch exception if 'start' is not in schedule.

                try:
                    if hh == schedule[day]['stop'] and instance.state == 'running':
                        logger.info("Stopping instance \"%s\"." %(instance.id))
                        stopped.append(instance.id)
                        ec2.stop_instances(instance_ids=[instance.id])
                except:
                    pass # catch exception if 'stop' is not in schedule.

            except KeyError as e:
                # 'schedule' tag not found, create if appropriate.
                create_schedule_tag(instance)
            except ValueError as e:
                # invalid JSON
                logger.error('Invalid value for tag \"schedule\" on instance \"%s\", please check!' %(instance.id))
Exemplo n.º 13
0
def f_stop(ec2):
    list_instances = return_list_instances(ec2)
    for instances in list_instances:
        if instances.state_code == 16:
            print "The instance %s is in state %s and will be stopped" % (instances.id, instances.state)
            ec2.stop_instances(instances.id)
            t_time.sleep(3)
            instances.update()
            while instances.state_code in [64]:
                print "Wainting for stop of instance %s, current state %s" % (instances.id, instances.state)
                t_time.sleep(15)
                instances.update()
            if instances.state_code == 80:
                print "The instance %s is %s" % (instances.id, instances.state)
            else:
                print "ERROR: The instance %s is %s" % (instances.id, instances.state)
        elif instances.state_code == 80:
            print "The instance %s is already stopped." % instances.id
        else:
            print "ERROR: Instance %s status is %s." % (instances.id, instances.state)
Exemplo n.º 14
0
def stop_instances(region, instance_list):
	ec2 = boto.ec2.connect_to_region(region)
	instance_ids = list(map(lambda x: x.id, instance_list))
	stopped = ec2.stop_instances(instance_ids=instance_ids)
	while True:
		try_again = False
		for inst in stopped:
			inst.update()
			if inst.state != 'stopped':
				try_again = True
		if try_again == True:
			time.sleep(2)
		else:
			break
Exemplo n.º 15
0
    # change instance ID appropriately  
    try:
         ec2.start_instances(instance_ids="i-12345678")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

def stopInstance():
    print "Stopping the instance..."

    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
         ec2.stop_instances(instance_ids="i-12345678")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

if __name__ == '__main__':
    main(
Exemplo n.º 16
0
    # change instance ID appropriately  
    try:
         ec2.start_instances(instance_ids="i-0dfa82e43e53d4bf7")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

def stopInstance():
    print "Stopping the instance..."

    try:
        ec2 = boto.ec2.connect_to_region("eu-west-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
         ec2.stop_instances(instance_ids="i-0dfa82e43e53d4bf7")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

if __name__ == '__main__':
main()
Exemplo n.º 17
0
def stop_instance(choice):
    print 'Stopping instance: ', choice
    ec2.stop_instances(instance_ids=choice)
    check_state(choice)
Exemplo n.º 18
0
def test_ec2_stop( ec2 ):
    ec2.stop_instances( [ "i-88895266" ] )
Exemplo n.º 19
0
def stop_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.stop_instances(instance_ids=[inst.id])
Exemplo n.º 20
0
    if action == "stop":
    	stopInstance()
    else:
    	print "Usage: python aws.py {stop}\n"


def stopInstance():
    print "Stopping the instance..."
    random_instance = random.randrange(0,3)
    random_instance_id = instance_list[random_instance]
    
    try:
        ec2 = boto.ec2.connect_to_region("us-west-2", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
        ec2.stop_instances(instance_ids=random_instance_id)
	
    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)

if __name__ == '__main__':
    main()
Exemplo n.º 21
0
    if "github.dcs.trend.com" in line:
        PrimaryIP = line.split(" ")[0]
    elif "github.replica.com" in line:
        ReplicaIP = line.split(" ")[0]
    else:
        newfile.write(line)

newfile.write(ReplicaIP+" github.dcs.trend.com\n")
newfile.write(PrimaryIP+" github.replica.com\n")

hostfile.close()
newfile.close()


#stop primary node
ec2 = boto.ec2.connect_to_region(awsRegion)
instList = ec2.get_only_instances()
for inst in instList:
    if inst.private_ip_address == PrimaryIP:
        ec2.stop_instances(inst.id)
        break

startFailover = time.time()
#replica node promoting
os.system("./ghe_replica_to_primary.py "+ReplicaIP)

print ("replica take place to primary   %s" % ( time.time() - startFailover ))

#exchange the hostname
os.system("sudo mv hosts /etc/hosts")
Exemplo n.º 22
0
        ec2.start_instances(instance_ids="i-0ea81734e91a6140c")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)


def stopInstance():
    print "Stopping the instance..."

    try:
        ec2 = boto.ec2.connect_to_region("ap-southeast-1", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        print(error1)
        sys.exit(0)

    try:
        ec2.stop_instances(instance_ids="i-0ea81734e91a6140c")

    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        print(error2)
        sys.exit(0)


if __name__ == '__main__':
    main()
Exemplo n.º 23
0
def test_ec2_stop(ec2):
    ec2.stop_instances(["i-88895266"])
Exemplo n.º 24
0
        return error2


# to stop an instance with given instance_id (i-......)
def stopInstance(input_id):
    print "Stopping the instance..."

    try:
        ec2 = boto.ec2.connect_to_region("us-west-2", **auth)

    except Exception, e1:
        error1 = "Error1: %s" % str(e1)
        return error1

    try:
        ec2.stop_instances(instance_ids=input_id)
        return "successfully stopped instance"
    except Exception, e2:
        error2 = "Error2: %s" % str(e2)
        return error2


# to list all the instances, output is a dict with instance_id, tag_name and status
def listInstances():
    print "Listing all the instances"

    ec2 = boto.ec2.connect_to_region('us-west-2', **auth)
    #--- for the id on which this is running
    nm = boto.utils.get_instance_metadata()['public-hostname']
    print nm
    # all running instances