Python boto 模块,ec2() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用boto.ec2()

项目:Stream-Framework-Bench    作者:GetStream    | 项目源码 | 文件源码
def connect():
    metadata = boto.utils.get_instance_metadata()
    region = metadata['placement']['availability-zone'][:-1]

    for role in metadata['iam']['security-credentials'].keys():
        conn = boto.ec2.connection.EC2Connection(
                region=boto.ec2.get_region(region),
                aws_access_key_id=metadata['iam']['security-credentials'][role]['AccessKeyId'],
                aws_secret_access_key=metadata['iam']['security-credentials'][role]['SecretAccessKey'],
                security_token=metadata['iam']['security-credentials'][role]['Token']
        )
        break

    return conn

#
# Print out private IPv4
#
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def _get_auto_scaling_group_lbs(self):
        """Returns a list of ELBs associated with self.instance_id
           indirectly through its auto scaling group membership"""

        try:
           asg = connect_to_aws(boto.ec2.autoscale, self.region, **self.aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
            self.module.fail_json(msg=str(e))

        asg_instances = asg.get_all_autoscaling_instances([self.instance_id])
        if len(asg_instances) > 1:
           self.module.fail_json(msg="Illegal state, expected one auto scaling group instance.")

        if not asg_instances:
           asg_elbs = []
        else:
           asg_name = asg_instances[0].group_name

           asgs = asg.get_all_groups([asg_name])
           if len(asg_instances) != 1:
              self.module.fail_json(msg="Illegal state, expected one auto scaling group.")

           asg_elbs = asgs[0].load_balancers

        return asg_elbs
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def find_igw(vpc_conn, vpc_id):
    """
    Finds the Internet gateway for the given VPC ID.

    Raises an AnsibleIgwSearchException if either no IGW can be found, or more
    than one found for the given VPC.

    Note that this function is duplicated in other ec2 modules, and should
    potentially be moved into potentially be moved into a shared module_utils
    """
    igw = vpc_conn.get_all_internet_gateways(
        filters={'attachment.vpc-id': vpc_id})

    if not igw:
        raise AnsibleIgwSearchException('No IGW found for VPC {0}'.
                                         format(vpc_id))
    elif len(igw) == 1:
        return igw[0].id
    else:
        raise AnsibleIgwSearchException('Multiple IGWs found for VPC {0}'.
                                        format(vpc_id))
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            filters = dict(default=None, type='dict')
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module)

    if region:
        try:
            connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
            module.fail_json(msg=str(e))
    else:
        module.fail_json(msg="region must be specified")

    list_ec2_instances(connection, module)
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def ec2_connect(module):

    """ Return an ec2 connection"""

    region, ec2_url, boto_params = get_aws_connection_info(module)

    # If we have a region specified, connect to its endpoint.
    if region:
        try:
            ec2 = connect_to_aws(boto.ec2, region, **boto_params)
        except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
            module.fail_json(msg=str(e))
    # Otherwise, no region so we fallback to the old connection method
    elif ec2_url:
        try:
            ec2 = boto.connect_ec2_endpoint(ec2_url, **boto_params)
        except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
            module.fail_json(msg=str(e))
    else:
        module.fail_json(msg="Either region or ec2_url must be specified")

    return ec2
项目:Django-Fabric-AWS-Py3    作者:ankit-maverick    | 项目源码 | 文件源码
def _create_ec2_instance():
    """
    Creates EC2 Instance
    """
    print(_yellow("Creating instance"))
    conn = boto.ec2.connect_to_region(ec2_region, aws_access_key_id=fabconf['AWS_ACCESS_KEY'], aws_secret_access_key=fabconf['AWS_SECRET_KEY'])

    image = conn.get_all_images(ec2_amis)

    reservation = image[0].run(1, 1, ec2_keypair, ec2_secgroups,
        instance_type=ec2_instancetype)

    instance = reservation.instances[0]
    conn.create_tags([instance.id], {"Name":fabconf['INSTANCE_NAME_TAG']})

    while instance.state == u'pending':
        print(_yellow("Instance state: %s" % instance.state))
        time.sleep(10)
        instance.update()

    print(_green("Instance state: %s" % instance.state))
    print(_green("Public dns: %s" % instance.public_dns_name))

    return instance.public_dns_name
项目:better-brenda    作者:simplecarnival    | 项目源码 | 文件源码
def blk_dev_map(opts, conf, itype, snapshots):
    if not int(conf.get('NO_EBS', '0')):
        bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
        snap = project_ebs_snapshot(conf)
        snap_id = translate_snapshot_name(conf, snap, snapshots)
        snap_description = []
        if snap_id:
            dev = utils.blkdev(0)
            bdm[dev] = boto.ec2.blockdevicemapping.EBSBlockDeviceType(snapshot_id=snap_id, delete_on_termination=True)
            snap_description.append((snap, snap_id, dev))
        i = 0
        for k in additional_ebs_iterator(conf):
            i += 1
            snap = parse_ebs_url(conf[k].split(',')[0])
            snap_id = translate_snapshot_name(conf, snap, snapshots)
            if snap_id:
                dev = utils.blkdev(i)
                bdm[dev] = boto.ec2.blockdevicemapping.EBSBlockDeviceType(snapshot_id=snap_id, delete_on_termination=True)
                snap_description.append((snap, snap_id, dev))
        istore_dev = add_instance_store(opts, conf, bdm, itype)
        return bdm, snap_description, istore_dev
    else:
        return None, None, None
项目:better-brenda    作者:simplecarnival    | 项目源码 | 文件源码
def blk_dev_map(opts, conf, itype, snapshots):
    if not int(conf.get('NO_EBS', '0')):
        bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
        snap = project_ebs_snapshot(conf)
        snap_id = translate_snapshot_name(conf, snap, snapshots)
        snap_description = []
        if snap_id:
            dev = utils.blkdev(0)
            bdm[dev] = boto.ec2.blockdevicemapping.EBSBlockDeviceType(snapshot_id=snap_id, delete_on_termination=True)
            snap_description.append((snap, snap_id, dev))
        i = 0
        for k in additional_ebs_iterator(conf):
            i += 1
            snap = parse_ebs_url(conf[k].split(',')[0])
            snap_id = translate_snapshot_name(conf, snap, snapshots)
            if snap_id:
                dev = utils.blkdev(i)
                bdm[dev] = boto.ec2.blockdevicemapping.EBSBlockDeviceType(snapshot_id=snap_id, delete_on_termination=True)
                snap_description.append((snap, snap_id, dev))
        istore_dev = add_instance_store(opts, conf, bdm, itype)
        return bdm, snap_description, istore_dev
    else:
        return None, None, None
项目:bigdata-tools    作者:kylebush    | 项目源码 | 文件源码
def mount_ebs_volumes(host_config):

    env.host_string = helper.get_env_host_string(host_config)
    env.user = helper.get_env_user(host_config)
    env.key_filename = helper.get_env_key_filename(host_config)

    sudo("apt-get -y install xfsprogs")

    for ebs in host_config['ec2-mounts']:

        device = ebs['device']
        mount = ebs['mount']

        sudo("mkdir -p {}".format(mount))

        sudo("mv /etc/fstab /etc/fstab.old")
        sudo("touch /etc/fstab")
        if sudo('mkfs.xfs -f {0}'.format(device), warn_only=True):
            run("echo '{0}\t{1}\txfs\tdefaults\t0\t0' | sudo tee -a /etc/fstab".format(device, mount))
            sudo('sudo mount -a')

        logger.info("EBS volume {} : {} mounted.".format(device, mount))
项目:alfred-ec2    作者:SoMuchToGrok    | 项目源码 | 文件源码
def get_recent_instances(region, profile_name):
    conn = boto.ec2.connect_to_region(region,
                                      profile_name=profile_name)
    reservations = conn.get_all_reservations()

    instances = []

    for res in reservations:
        for i in res.instances:
            if i.state != 'running':
                continue
            name = 'Name' in i.tags and i.tags['Name'] or i.dns_name
            if i.private_ip_address:
                desc = i.private_ip_address + u' [' + i.instance_type + ']'
            else:
                desc = u' [' + i.instance_type + ']'
            instances.append({'desc': desc,
                              'ip': i.private_ip_address,
                              'name': name})

    return instances
项目:ansible-oss    作者:sailthru    | 项目源码 | 文件源码
def lookup_instance(self, name):
        try:
            ec2_conn = boto.ec2.connect_to_region(region_name=self.region, profile_name=self.profile)
        except Exception as e:
            raise AnsibleError(e)
        filters = {self.filter: name}

        reservations = ec2_conn.get_all_instances(filters={'tag:name': 'nat-main'})

        instances = [i for r in reservations for i in r.instances]

        for instance in instances:

            if instance.state == 'terminated' or instance.state == 'stopped':
                continue
            return instance.id.encode('utf-8')

        return name
项目:openshift-ansible-contrib    作者:openshift    | 项目源码 | 文件源码
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            filters = dict(default=None, type='dict')
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module)

    if region:
        try:
            connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, StandardError), e:
            module.fail_json(msg=str(e))
    else:
        module.fail_json(msg="region must be specified")

    list_ec2_volumes(connection, module)
项目:openshift-ansible    作者:nearform    | 项目源码 | 文件源码
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            filters = dict(default=None, type='dict')
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    region, ec2_url, aws_connect_params = get_aws_connection_info(module)

    if region:
        try:
            connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, StandardError), e:
            module.fail_json(msg=str(e))
    else:
        module.fail_json(msg="region must be specified")

    list_ec2_volumes(connection, module)
项目:LIS-Tempest    作者:LIS    | 项目源码 | 文件源码
def _keystone_aws_get(self):
        import keystoneclient.v2_0.client

        keystone = keystoneclient.v2_0.client.Client(**self.ks_cred)
        ec2_cred_list = keystone.ec2.list(keystone.auth_user_id)
        ec2_cred = None
        for cred in ec2_cred_list:
            if cred.tenant_id == keystone.auth_tenant_id:
                ec2_cred = cred
                break
        else:
            ec2_cred = keystone.ec2.create(keystone.auth_user_id,
                                           keystone.auth_tenant_id)
        if not all((ec2_cred, ec2_cred.access, ec2_cred.secret)):
            raise exceptions.NotFound("Unable to get access and secret keys")
        return ec2_cred
项目:drift    作者:dgnorth    | 项目源码 | 文件源码
def get_ec2_instances(region, filters=None):
    """
    Returns all EC2 instances on the specified region.
    'filters' is passed to the 'get_all_reservations' function.
    """
    conn = boto.ec2.connect_to_region(region)

    reservations = conn.get_all_reservations(filters=filters)
    instances = [i for r in reservations for i in r.instances]
    return instances
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def _get_connection(self):
        if self._conn is not None:
            return
        self._conn = boto.ec2.connect_to_region(
            self._region,
            aws_access_key_id=self._aws_access_key_id,
            aws_secret_access_key=self._aws_secret_access_key)
项目:kuberdock-platform    作者:cloudlinux    | 项目源码 | 文件源码
def detach_ebs(aws_access_key_id, aws_secret_access_key, devices):
    import boto
    import boto.ec2
    meta = get_aws_instance_meta(boto.utils)
    connection = boto.ec2.connect_to_region(
        meta['region'],
        aws_access_key_id=aws_access_key_id,
        aws_secret_access_key=aws_secret_access_key
    )
    bd_mapping = get_aws_block_device_mapping(
        connection, meta['instance-id']
    )
    for key, bd in bd_mapping.iteritems():
        if key in devices:
            connection.detach_volume(bd.volume_id)
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def __init__(self):
        self.region = None
        self.name = None
        self.instance_type = None
        self.quantity = 0
        self.zone = None
        self.ami = None
        self.groups = []
        self.key = None
        self.ec2 = None
        self.config = None
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def set_region(self, region=None):
        if region:
            self.region = region
        else:
            l = [(r, r.name, r.endpoint) for r in boto.ec2.regions()]
            self.region = self.choose_from_list(l, prompt='Choose Region')
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def set_zone(self, zone=None):
        if zone:
            self.zone = zone
        else:
            l = [(z, z.name, z.state) for z in self.ec2.get_all_zones()]
            self.zone = self.choose_from_list(l, prompt='Choose Availability Zone')
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def set_ami(self, ami=None):
        if ami:
            self.ami = ami
        else:
            l = [(a, a.id, a.location) for a in self.ec2.get_all_images()]
            self.ami = self.choose_from_list(l, prompt='Choose AMI')
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def add_group(self, group=None):
        if group:
            self.groups.append(group)
        else:
            l = [(s, s.name, s.description) for s in self.ec2.get_all_security_groups()]
            self.groups.append(self.choose_from_list(l, prompt='Choose Security Group'))
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def update_config(self):
        if not self.config.has_section('Credentials'):
            self.config.add_section('Credentials')
            self.config.set('Credentials', 'aws_access_key_id', self.ec2.aws_access_key_id)
            self.config.set('Credentials', 'aws_secret_access_key', self.ec2.aws_secret_access_key)
        if not self.config.has_section('Pyami'):
            self.config.add_section('Pyami')
        sdb_domain = get_domain()
        if sdb_domain:
            self.config.set('Pyami', 'server_sdb_domain', sdb_domain)
            self.config.set('Pyami', 'server_sdb_name', self.name)
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def enter(self, **params):
        self.region = params.get('region', self.region)
        if not self.region:
            self.set_region()
        self.ec2 = self.region.connect()
        self.name = params.get('name', self.name)
        if not self.name:
            self.set_name()
        self.instance_type = params.get('instance_type', self.instance_type)
        if not self.instance_type:
            self.set_instance_type()
        self.zone = params.get('zone', self.zone)
        if not self.zone:
            self.set_zone()
        self.quantity = params.get('quantity', self.quantity)
        if not self.quantity:
            self.set_quantity()
        self.ami = params.get('ami', self.ami)
        if not self.ami:
            self.set_ami()
        self.groups = params.get('groups', self.groups)
        if not self.groups:
            self.add_group()
        self.key = params.get('key', self.key)
        if not self.key:
            self.set_key()
        self.config = params.get('config', self.config)
        if not self.config:
            self.set_config()
        self.update_config()
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def __init__(self, key, secret, account_id, instance, region, rate):
        # Connect to region
        self.conn = boto.ec2.connect_to_region(region, aws_access_key_id=key,
                                               aws_secret_access_key=secret)
        self.instance = instance
        self.rate = float(rate)
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def update_image(module, ec2):
    """
    Updates AMI
    """

    image_id = module.params.get('image_id')
    launch_permissions = module.params.get('launch_permissions')
    if 'user_ids' in launch_permissions:
        launch_permissions['user_ids'] = [str(user_id) for user_id in launch_permissions['user_ids']]

    img = ec2.get_image(image_id)
    if img == None:
        module.fail_json(msg = "Image %s does not exist" % image_id, changed=False)

    try:
        set_permissions = img.get_launch_permissions()
        if set_permissions != launch_permissions:
            if ('user_ids' in launch_permissions and launch_permissions['user_ids']) or ('group_names' in launch_permissions and launch_permissions['group_names']):
                res = img.set_launch_permissions(**launch_permissions)
            elif ('user_ids' in set_permissions and set_permissions['user_ids']) or ('group_names' in set_permissions and set_permissions['group_names']):
                res = img.remove_launch_permissions(**set_permissions)
            else:
                module.exit_json(msg="AMI not updated", launch_permissions=set_permissions, changed=False)
            module.exit_json(msg="AMI launch permissions updated", launch_permissions=launch_permissions, set_perms=set_permissions, changed=True)
        else:
            module.exit_json(msg="AMI not updated", launch_permissions=set_permissions, changed=False)

    except boto.exception.BotoServerError as e:
        module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def _get_instance_lbs(self, ec2_elbs=None):
        """Returns a list of ELBs attached to self.instance_id
        ec2_elbs: an optional list of elb names that will be used
                  for elb lookup instead of returning what elbs
                  are attached to self.instance_id"""

        if not ec2_elbs:
           ec2_elbs = self._get_auto_scaling_group_lbs()

        try:
            elb = connect_to_aws(boto.ec2.elb, self.region, **self.aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
            self.module.fail_json(msg=str(e))

        elbs = []
        marker = None
        while True:
            try:
                newelbs = elb.get_all_load_balancers(marker=marker)
                marker = newelbs.next_marker
                elbs.extend(newelbs)
                if not marker:
                    break
            except TypeError:
                # Older version of boto do not allow for params
                elbs = elb.get_all_load_balancers()
                break

        if ec2_elbs:
            lbs = sorted(lb for lb in elbs if lb.name in ec2_elbs)
        else:
            lbs = []
            for lb in elbs:
                for info in lb.instances:
                    if self.instance_id == info.id:
                        lbs.append(lb)
        return lbs
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def _get_elb_connection(self):
        try:
            return connect_to_aws(boto.ec2.elb, self.region,
                                  **self.aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
            self.module.fail_json(msg=str(e))
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def _get_ec2_connection(self):
        try:
            return connect_to_aws(boto.ec2, self.region,
                                  **self.aws_connect_params)
        except (boto.exception.NoAuthHandlerFound, StandardError) as e:
            self.module.fail_json(msg=str(e))
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def _check_attribute_support(self, attr):
        return hasattr(boto.ec2.elb.attributes.LbAttributes(), attr)
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            filters = dict(default=None, type='dict')
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    if HAS_BOTO3:
        region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)

        if region:
            connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params)
        else:
            module.fail_json(msg="region must be specified")

        list_ec2_snapshots_boto3(connection, module)
    else:
        region, ec2_url, aws_connect_params = get_aws_connection_info(module)

        if region:
            try:
                connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
            except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
                module.fail_json(msg=str(e))
        else:
            module.fail_json(msg="region must be specified")

        list_eni(connection, module)
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def copy_image(module, ec2):
    """
    Copies an AMI

    module : AnsibleModule object
    ec2: authenticated ec2 connection object
    """

    source_region = module.params.get('source_region')
    source_image_id = module.params.get('source_image_id')
    name = module.params.get('name')
    description = module.params.get('description')
    encrypted = module.params.get('encrypted')
    kms_key_id = module.params.get('kms_key_id')
    tags = module.params.get('tags')
    wait_timeout = int(module.params.get('wait_timeout'))
    wait = module.params.get('wait')

    try:
        params = {'source_region': source_region,
                  'source_image_id': source_image_id,
                  'name': name,
                  'description': description,
                  'encrypted': encrypted,
                  'kms_key_id': kms_key_id
        }

        image_id = ec2.copy_image(**params).image_id
    except boto.exception.BotoServerError as e:
        module.fail_json(msg="%s: %s" % (e.error_code, e.error_message))

    img = wait_until_image_is_recognized(module, ec2, wait_timeout, image_id, wait)

    img = wait_until_image_is_copied(module, ec2, wait_timeout, img, image_id, wait)

    register_tags_if_any(module, ec2, tags, image_id)

    module.exit_json(msg="AMI copy operation complete", image_id=image_id, state=img.state, changed=True)


# register tags to the copied AMI
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def wait_until_image_is_copied(module, ec2, wait_timeout, img, image_id, wait):
    wait_timeout = time.time() + wait_timeout
    while wait and wait_timeout > time.time() and (img is None or img.state != 'available'):
        img = ec2.get_image(image_id)
        time.sleep(3)
    if wait and wait_timeout <= time.time():
        # waiting took too long
        module.fail_json(msg="timed out waiting for image to be copied")
    return img


# wait until the image is recognized.
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def wait_until_image_is_recognized(module, ec2, wait_timeout, image_id, wait):
    for i in range(wait_timeout):
        try:
            return ec2.get_image(image_id)
        except boto.exception.EC2ResponseError as e:
            # This exception we expect initially right after registering the copy with EC2 API
            if 'InvalidAMIID.NotFound' in e.error_code and wait:
                time.sleep(1)
            else:
                # On any other exception we should fail
                module.fail_json(
                    msg="Error while trying to find the new image. Using wait=yes and/or a longer wait_timeout may help: " + str(
                        e))
    else:
        module.fail_json(msg="timed out waiting for image to be recognized")
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(dict(
        source_region=dict(required=True),
        source_image_id=dict(required=True),
        name=dict(),
        description=dict(default=""),
        encrypted=dict(type='bool', required=False),
        kms_key_id=dict(type='str', required=False),
        wait=dict(type='bool', default=False),
        wait_timeout=dict(default=1200),
        tags=dict(type='dict')))

    module = AnsibleModule(argument_spec=argument_spec)

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    try:
        ec2 = ec2_connect(module)
    except boto.exception.NoAuthHandlerFound as e:
        module.fail_json(msg=str(e))

    try:
        region, ec2_url, boto_params = get_aws_connection_info(module)
    except boto.exception.NoAuthHandlerFound as e:
        module.fail_json(msg=str(e))

    if not region:
        module.fail_json(msg="region must be specified")

    copy_image(module, ec2)
项目:ngas    作者:ICRAR    | 项目源码 | 文件源码
def connect():
    import boto.ec2
    default_if_empty(env, 'AWS_PROFILE', DEFAULT_AWS_PROFILE)
    default_if_empty(env, 'AWS_REGION',  DEFAULT_AWS_REGION)
    return boto.ec2.connect_to_region(env.AWS_REGION, profile_name=env.AWS_PROFILE)
项目:ngas    作者:ICRAR    | 项目源码 | 文件源码
def create_aws_instances():
    """
    Create AWS instances and let Fabric point to them

    This method creates AWS instances and points the fabric environment to them with
    the current public IP and username.
    """

    default_if_empty(env, 'AWS_KEY_NAME',      DEFAULT_AWS_KEY_NAME)
    default_if_empty(env, 'AWS_INSTANCE_NAME', default_instance_name)

    # Create the key pair and security group if necessary
    conn = connect()
    aws_create_key_pair(conn)
    sgid = check_create_aws_sec_group(conn)

    # Create the instance in AWS
    host_names = create_instances(conn, sgid)

    # Update our fabric environment so from now on we connect to the
    # AWS machine using the correct user and SSH private key
    env.hosts = host_names
    env.key_filename = key_filename(env.AWS_KEY_NAME)
    if env.AWS_AMI_NAME in ['CentOS', 'SLES']:
        env.user = 'root'
    else:
        env.user = 'ec2-user'

    # Instances have started, but are not usable yet, make sure SSH has started
    puts('Started the instance(s) now waiting for the SSH daemon to start.')
    execute(check_ssh, timeout=300)
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def __init__(self):
        self.region = None
        self.name = None
        self.instance_type = None
        self.quantity = 0
        self.zone = None
        self.ami = None
        self.groups = []
        self.key = None
        self.ec2 = None
        self.config = None
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def set_region(self, region=None):
        if region:
            self.region = region
        else:
            l = [(r, r.name, r.endpoint) for r in boto.ec2.regions()]
            self.region = self.choose_from_list(l, prompt='Choose Region')
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def set_zone(self, zone=None):
        if zone:
            self.zone = zone
        else:
            l = [(z, z.name, z.state) for z in self.ec2.get_all_zones()]
            self.zone = self.choose_from_list(l, prompt='Choose Availability Zone')
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def set_ami(self, ami=None):
        if ami:
            self.ami = ami
        else:
            l = [(a, a.id, a.location) for a in self.ec2.get_all_images()]
            self.ami = self.choose_from_list(l, prompt='Choose AMI')
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def add_group(self, group=None):
        if group:
            self.groups.append(group)
        else:
            l = [(s, s.name, s.description) for s in self.ec2.get_all_security_groups()]
            self.groups.append(self.choose_from_list(l, prompt='Choose Security Group'))
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def update_config(self):
        if not self.config.has_section('Credentials'):
            self.config.add_section('Credentials')
            self.config.set('Credentials', 'aws_access_key_id', self.ec2.aws_access_key_id)
            self.config.set('Credentials', 'aws_secret_access_key', self.ec2.aws_secret_access_key)
        if not self.config.has_section('Pyami'):
            self.config.add_section('Pyami')
        sdb_domain = get_domain()
        if sdb_domain:
            self.config.set('Pyami', 'server_sdb_domain', sdb_domain)
            self.config.set('Pyami', 'server_sdb_name', self.name)
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def enter(self, **params):
        self.region = params.get('region', self.region)
        if not self.region:
            self.set_region()
        self.ec2 = self.region.connect()
        self.name = params.get('name', self.name)
        if not self.name:
            self.set_name()
        self.instance_type = params.get('instance_type', self.instance_type)
        if not self.instance_type:
            self.set_instance_type()
        self.zone = params.get('zone', self.zone)
        if not self.zone:
            self.set_zone()
        self.quantity = params.get('quantity', self.quantity)
        if not self.quantity:
            self.set_quantity()
        self.ami = params.get('ami', self.ami)
        if not self.ami:
            self.set_ami()
        self.groups = params.get('groups', self.groups)
        if not self.groups:
            self.add_group()
        self.key = params.get('key', self.key)
        if not self.key:
            self.set_key()
        self.config = params.get('config', self.config)
        if not self.config:
            self.set_config()
        self.update_config()
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def __init__(self):
        self.region = None
        self.name = None
        self.instance_type = None
        self.quantity = 0
        self.zone = None
        self.ami = None
        self.groups = []
        self.key = None
        self.ec2 = None
        self.config = None
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def set_region(self, region=None):
        if region:
            self.region = region
        else:
            l = [(r, r.name, r.endpoint) for r in boto.ec2.regions()]
            self.region = self.choose_from_list(l, prompt='Choose Region')
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def set_zone(self, zone=None):
        if zone:
            self.zone = zone
        else:
            l = [(z, z.name, z.state) for z in self.ec2.get_all_zones()]
            self.zone = self.choose_from_list(l, prompt='Choose Availability Zone')
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def set_ami(self, ami=None):
        if ami:
            self.ami = ami
        else:
            l = [(a, a.id, a.location) for a in self.ec2.get_all_images()]
            self.ami = self.choose_from_list(l, prompt='Choose AMI')
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def add_group(self, group=None):
        if group:
            self.groups.append(group)
        else:
            l = [(s, s.name, s.description) for s in self.ec2.get_all_security_groups()]
            self.groups.append(self.choose_from_list(l, prompt='Choose Security Group'))
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def update_config(self):
        if not self.config.has_section('Credentials'):
            self.config.add_section('Credentials')
            self.config.set('Credentials', 'aws_access_key_id', self.ec2.aws_access_key_id)
            self.config.set('Credentials', 'aws_secret_access_key', self.ec2.aws_secret_access_key)
        if not self.config.has_section('Pyami'):
            self.config.add_section('Pyami')
        sdb_domain = get_domain()
        if sdb_domain:
            self.config.set('Pyami', 'server_sdb_domain', sdb_domain)
            self.config.set('Pyami', 'server_sdb_name', self.name)