def parse_AWS(): """ parse EC2_BACKUP_FLAGS_AWS, which determines the details of instance """ log.info("parsing aws config ...") try: ins_conf = os.environ['EC2_BACKUP_FLAGS_AWS'] except KeyError: log.error("Environment variable EC2_BACKUP_FLAGS_AWS not set.") sys.exit(1) opts, args = getopt.getopt(ins_conf.split(), "i:t:k:g:", ["image-id=","instance-type=", "key-name=", "security-groups="]) for o, a in opts: if o in ("-k", "--key-name"): dict_ins['key-name'] = a elif o in ("-g", "--security-groups"): dict_ins['security-groups'] = a elif o in ("-i", "--image-id"): dict_ins['image-id'] = a elif o in ("-t", "--instance-type"): dict_ins['instance-type'] = a else: assert False, "unhandled option: " + o
def parse_SSH(): """ parse ssh option,get private key """ log.info("parsing ssh config ...") try: ssh_conf = os.environ['EC2_BACKUP_FLAGS_SSH'] except KeyError: log.error("Environment variable EC2_BACKUP_FLAGS_SSH not set.") sys.exit(1) lt = ssh_conf.split() if lt[0] == "-i": return lt[1].strip() else: log.error("Unrecognized ssh option") sys.exit(1)
def attach(volume_id=None, src_dir="/"): if(verbose): log.info("start attaching...") """ Attach volume """ global ins conn = boto.ec2.connect_to_region(dict_aws['region'], aws_access_key_id=dict_aws['key_id'], aws_secret_access_key=dict_aws['secret_key'] ) log.info("Connect to region: " + str(conn)) reservations = conn.run_instances( image_id=dict_ins['image-id'], key_name=dict_ins['key-name'], instance_type=dict_ins['instance-type'], security_groups=[dict_ins['security-groups']] ) ins = reservations.instances[0] status = ins.update() while status != 'running': log.info("wating for running, current status: " + str(status)) time.sleep(10) status = ins.update() log.info("Running instance %s: key %s, group %s." %(str(ins.id), dict_ins['key-name'], dict_ins['security-groups']) ) if volume_id is None: conv = 1024*1024*1024 sz = 2 * worker.get_size(src_dir) sz = int((sz+conv-1)/conv) vol = conn.create_volume(sz, ins.placement) volume_id = vol.id log.info("Create volume: " + str(volume_id)) status = vol.update() while status != 'available': log.info("wating for available, current status: " + str(status) ) time.sleep(5) status = vol.update() log.info("attach volume " + str(volume_id)) dest = "/dev/sdz" print if conn.attach_volume(volume_id, ins.id , dest) == False: log.error("Attach failed.") sys.exit(1) log.info( "Attached volume %s to %s" %(volume_id, dest) ) return ins.ip_address, '/dev/xvdz', volume_id