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)
def startInstance(ec2Id): print "Starting instance..." ec2 = boto.ec2.connect_to_region(region, aws_access_key_id=accessKeyId, aws_secret_access_key=accessKeySecret) ec2.start_instances(instance_ids=ec2Id) print('Instance Id : ' + ec2Id) print('Command processed...') time.sleep(5) print('Instance Status : ' + statusInstance(ec2Id))
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
def startInstance(id1, ec2): print "Starting the instance..." #ec2 = boto.ec2.connect_to_region("us-east-2", **auth) # change instance ID appropriately try: ec2.start_instances(instance_ids=id1) except Exception, e2: error1 = "Error1: %s" % str(e2) print(error1) sys.exit(0)
def f_start(ec2, vpc, objects): # Create list of objects to print instance_list, instance_print, vpn_list, vpn_print = c_object_list(objects) if instance_print: # Start instance print('Instance Starting 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': print('ID: ' + inst.instances[0].id + ' is already running.') elif inst.instances[0].state == 'stopped': ec2.start_instances(instance_ids=inst.instances[0].id) print('ID: ' + inst.instances[0].id + ' has been started.') else: print('ID: ' + inst.instances[0].id + ' is under the ' + inst.instances[0].state + ' state.') if vpn_print: # Create vpn (The list of vpn IDs is irrelevant in this case as they are being created) print('\n' + 'Vpn Starting Process >>>') vpn_available = False vpns = vpc.get_all_vpn_connections() for v in vpns: if v.vpn_gateway_id == 'vgw-2271ac3c' and v.state == 'available': vpn_available = True print('ID: ' + v.id + ' is already available.') break if not vpn_available: vpc.create_vpn_connection('ipsec.1', 'cgw-5172af4f', 'vgw-2271ac3c', static_routes_only=True, dry_run=False) # Wait 30s before start trying to set the static route time.sleep(30) for tries in range(45): # This give a maximum waiting time of 300s vpns_retry = vpc.get_all_vpn_connections() for v_retry in vpns_retry: if v_retry.vpn_gateway_id == 'vgw-2271ac3c' and v_retry.state == 'available': vpn_available = True print('ID: ' + v_retry.id + ' is available.') # Create static route for the local network vpc.create_vpn_connection_route('10.0.0.0/16', v_retry.id, dry_run=False) # Exit for loop break if vpn_available: # Exit for loop break else: # Sleep 6s before another try time.sleep(6) return
def startInstance(): print ("Starting 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.start_instances(instance_ids="") except Exception as e2: error2 = "Error2: %s" % str(e2) print(error2) sys.exit(0)
def start_instances(ec2, to_start=None): """Ensure instances are running Args: ec2: boto ec2 object to_start: list, instances to start """ if to_start: logger.info('Starting instances: %s' % to_start) if not DRY_RUN: ec2.start_instances(to_start) else: logger.debug('Nothing to start')
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 startInstance(): print("Starting the instance...") # change "eu-west-1" region if different 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) # change instance ID appropriately try: ec2.start_instances(instance_ids="i-06fc2d09c9b6bace4") except Exception as e2: error2 = "Error2: %s" % str(e2) print(error2) sys.exit(0) print(".......................") print("Started the instance...")
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))
def f_start(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 started" % (instances.id, instances.state) ec2.start_instances(instances.id) t_time.sleep(3) instances.update() while instances.state_code in [0]: print "Wainting for start of instance %s, current state %s" % (instances.id, instances.state) t_time.sleep(15) instances.update() if instances.state_code == 16: 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 == 16: print "The instance %s is already started." % instances.id else: print "ERROR: Instance %s status is %s." % (instances.id, instances.state)
def startInstance(N, D): print("Starting the instance...") # change "eu-west-1" region if different 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) # change instance ID appropriately try: ec2.start_instances(instance_ids="i-078f12dd0854c092e") except Exception as e2: error2 = "Error2: %s" % str(e2) print(error2) sys.exit(0) print("Instance starting with %s and %s" % (N, D))
def start_instances(region, instance_ids): ec2 = boto.ec2.connect_to_region(region) instances = ec2.start_instances(instance_ids=instance_ids) started = True while True: for i in instances: i.update() if i.state != 'running': started = False if started == False: started = True time.sleep(5) else: break return instances
def startInstance(): print "Starting the instance..." # change "eu-west-1" region if different try: ec2 = boto.ec2.connect_to_region("eu-west-1", **auth) except Exception, e1: error1 = "Error1: %s" % str(e1) print(error1) sys.exit(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)
def startInstance(): print "Starting the instance..." # change "eu-west-1" region if different try: ec2 = boto.ec2.connect_to_region("eu-west-1", **auth) except Exception, e1: error1 = "Error1: %s" % str(e1) print(error1) sys.exit(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)
def start_instance(choice): print 'Starting up instance: ', choice ec2.start_instances(instance_ids=choice) check_state(choice)
for line in hostfile.readlines(): if "github.dcs.trend.com" in line: PrimaryIP = line.split(" ")[0] elif "github.replica.com" in line: ReplicaIP = line.split(" ")[0] hostfile.close() startResuming = time.time() #start replica node ec2 = boto.ec2.connect_to_region(awsRegion) instList = ec2.get_only_instances() for inst in instList: if inst.private_ip_address == ReplicaIP: ec2.start_instances(inst.id) break startReplicaSetup = time.time() #resuming replica os.system("./ghe_replica_setup.py "+PrimaryIP+" "+ReplicaIP) endResume = time.time() print ("---------- time summery --------") print ("total time %s" % ( endResume - startResuming )) print ("reboot replica node %s" % ( startReplicaSetup - startResuming )) print ("replica setup %s" % ( endResume - startReplicaSetup)) print ("--------------------------------")
def start_instances(location, placement_group='*'): ec2 = boto.ec2.connect_to_region() instances = ec2.get_only_instances( filters={"placement-group-name": placement_group}) for inst in instances: ec2.start_instances(instance_ids=[inst.id])
instances = {"server1": "i-1234556778"} if instance_name not in instances: print "Invalid instance name. Available: " print instances.keys() sys.exit(0) startInstance(instances[instance_name],reboot) def startInstance(instance_id, reboot): print "Starting 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: if reboot: ec2.reboot_instances(instance_ids=instance_id) else: ec2.start_instances(instance_ids=instance_id) except Exception, e2: error2 = "Error2: %s" % str(e2) print(error2) sys.exit(0) if __name__ == '__main__': main()
def startInstance(): printChk("Starting the instance...") # change "eu-west-1" region if different try: ec2 = boto.ec2.connect_to_region("eu-west-1", **auth) except Exception, e1: error1 = "Error1: %s" % str(e1) print(error1) sys.exit(0) # change instance ID appropriately try: listInst = ec2.start_instances(instance_ids="i-12345678") except Exception, e2: error2 = "Error2: %s" % str(e2) print(error2) sys.exit(0) # get IP address - update at least once to get IP printChk("Waiting for instance to run...") while True: listInst[0].update() if listInst[0].state == 'running': break sleep(3) printChk("IP address: ")
ReplicaIP = "" for line in hostfile.readlines(): if "github.dcs.trend.com" in line: PrimaryIP = line.split(" ")[0] elif "github.replica.com" in line: ReplicaIP = line.split(" ")[0] hostfile.close() startResuming = time.time() #start replica node ec2 = boto.ec2.connect_to_region(awsRegion) instList = ec2.get_only_instances() for inst in instList: if inst.private_ip_address == ReplicaIP: ec2.start_instances(inst.id) break startReplicaSetup = time.time() #resuming replica os.system("./ghe_replica_setup.py " + PrimaryIP + " " + ReplicaIP) endResume = time.time() print("---------- time summery --------") print("total time %s" % (endResume - startResuming)) print("reboot replica node %s" % (startReplicaSetup - startResuming)) print("replica setup %s" % (endResume - startReplicaSetup)) print("--------------------------------")
def StartInstance(InstanceID): print "Starting Instance", InstanceID ec2.start_instances(InstanceID)
def startInstance(): print "Starting the instance..." # change "eu-west-1" region if different try: ec2 = boto.ec2.connect_to_region("ap-southeast-1", **auth) except Exception, e1: error1 = "Error1: %s" % str(e1) print(error1) sys.exit(0) # change instance ID appropriately try: 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)
#!/usr/bin/env python import boto.ec2 aws_access_key_id = raw_input = ("Please enter the aws_access_key_id: ") aws_secret_access_key = raw_input = ("Please enter the aws_access_key_id: ") auth = { "aws_access_key_id": aws_access_key_id, "aws_secret_access_key": aws_secret_access_key } ec2 = boto.ec2.connect_to_region("eu-west-2", **auth) print(ec2.get_all_instance_status()) print(ec2.get_all_instances()) for reservation in ec2.get_all_instances(): print(reservation) print(reservation.instances[0]) ec2.start_instances(reservation.instances[0].id)