Example #1
0
def modify_dot_attribute(module, ec2, instance, device_name):
    """ Modify delete_on_termination attribute """

    delete_on_termination = module.params.get('delete_on_termination')
    changed = False

    try:
        instance.update()
        dot = instance.block_device_mapping[device_name].delete_on_termination
    except boto.exception.BotoServerError as e:
        module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))

    if delete_on_termination != dot:
        try:
            bdt = BlockDeviceType(delete_on_termination=delete_on_termination)
            bdm = BlockDeviceMapping()
            bdm[device_name] = bdt

            ec2.modify_instance_attribute(instance_id=instance.id, attribute='blockDeviceMapping', value=bdm)

            while instance.block_device_mapping[device_name].delete_on_termination != delete_on_termination:
                time.sleep(3)
                instance.update()
            changed = True
        except boto.exception.BotoServerError as e:
            module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))

    return changed
Example #2
0
def modify_dot_attribute(module, ec2, instance, device_name):
    """ Modify delete_on_termination attribute """

    delete_on_termination = module.params.get('delete_on_termination')
    changed = False

    try:
        instance.update()
        dot = instance.block_device_mapping[device_name].delete_on_termination
    except boto.exception.BotoServerError as e:
        module.fail_json(msg="%s: %s" % (e.error_code, e.error_message))

    if delete_on_termination != dot:
        try:
            bdt = BlockDeviceType(delete_on_termination=delete_on_termination)
            bdm = BlockDeviceMapping()
            bdm[device_name] = bdt

            ec2.modify_instance_attribute(instance_id=instance.id,
                                          attribute='blockDeviceMapping',
                                          value=bdm)

            while instance.block_device_mapping[
                    device_name].delete_on_termination != delete_on_termination:
                time.sleep(3)
                instance.update()
            changed = True
        except boto.exception.BotoServerError as e:
            module.fail_json(msg="%s: %s" % (e.error_code, e.error_message))

    return changed
Example #3
0
    def register_volumes_for_delete(self, hosts):
        ec2 = self.connect_ec2()

        # for each host, modify the instance attribute to enable automatic
        # volume deletion automatically when the host is terminated
        for h in hosts:
            if not h.instance_id:
                logger.info('Host {0} has no instance ID...skipping volume '
                            'delete.'.format(h))
                continue

            # get current block device mappings
            _, devices = ec2.get_instance_attribute(
                h.instance_id,
                'blockDeviceMapping').popitem()

            # find those devices that aren't already registered for deletion
            # and build a list of the modify strings
            mods = []
            for device_name, device in devices.iteritems():
                if not device.delete_on_termination:
                    mods.append('{0}=true'.format(device_name))

            # use the modify strings to change the existing volumes flag
            if mods:
                ec2.modify_instance_attribute(h.instance_id,
                                              'blockDeviceMapping',
                                              mods)

            # for each volume, rename them so we can create new volumes with
            # the same now, just in case
            for v in h.volumes.all():
                if not v.volume_id:
                    logger.warn('{0!r} missing volume_id. Skipping delete '
                                'retag.'.format(v))
                    continue
                name = 'stackdio::volume::{0!s}-DEL-{1}'.format(v.id,
                                                                uuid4().hex)
                logger.info('tagging volume {0}: {1}'.format(v.volume_id,
                                                             name))
                ec2.create_tags([v.volume_id], {
                    'Name': name,
                })
Example #4
0
    def register_volumes_for_delete(self, hosts):
        ec2 = self.connect_ec2()

        # for each host, modify the instance attribute to enable automatic
        # volume deletion automatically when the host is terminated
        for h in hosts:
            if not h.instance_id:
                logger.info('Host {0} has no instance ID...skipping volume '
                            'delete.'.format(h))
                continue

            # get current block device mappings
            _, devices = ec2.get_instance_attribute(
                h.instance_id, 'blockDeviceMapping').popitem()

            # find those devices that aren't already registered for deletion
            # and build a list of the modify strings
            mods = []
            for device_name, device in devices.items():
                if not device.delete_on_termination:
                    mods.append('{0}=true'.format(device_name))

            # use the modify strings to change the existing volumes flag
            if mods:
                ec2.modify_instance_attribute(h.instance_id,
                                              'blockDeviceMapping', mods)

            # for each volume, rename them so we can create new volumes with
            # the same now, just in case
            for v in h.volumes.all():
                if not v.volume_id:
                    logger.warning(
                        '{0!r} missing volume_id. Skipping delete retag.'.
                        format(v))
                    continue
                name = 'stackdio::volume::{0!s}-DEL-{1}'.format(
                    v.id,
                    uuid4().hex)
                logger.info('tagging volume {0}: {1}'.format(
                    v.volume_id, name))
                ec2.create_tags([v.volume_id], {
                    'Name': name,
                })
Example #5
0
                                key_name='east_keypair',
                                instance_type='t2.micro',
                                security_group_ids=[sg_public.id],
                                subnet_id=pubsub.id)

inst = reservation.instances[0]
inst.add_tag("Name", "NAT Instance by Python")
print "Tagged the instance!"

while inst.state == 'pending':
    time.sleep(5)
    inst.update()

#Change the attribute for NAT'ing
ec2.modify_instance_attribute(inst.id,
                              attribute='sourceDestCheck',
                              value=False)
print "Attribute changed!"

#Assign elastic IP 54.173.234.49 to the NAT Instance
eip = ec2.allocate_address(None, False)
eip.associate(inst.id, None, None, False, False)

#========================================================================

#========================================================================
# Create the Private Instance
ec2 = boto.ec2.connect_to_region('us-east-1')
reservation = ec2.run_instances('ami-b66ed3de',
                                key_name='east_keypair',
                                instance_type='t2.micro',
def _launch_instances_abort_on_error(ami,
                                     bid,
                                     count,
                                     instance_type,
                                     subnet,
                                     assign_public_ip,
                                     source_dest_check,
                                     placement_group,
                                     disks,
                                     security_group_ids,
                                     tags=None):
    ephemeral_idx = 0
    bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
    if disks is not None:
        for disk in disks:
            bdm[disk] = boto.ec2.blockdevicemapping.BlockDeviceType(
                ephemeral_name='ephemeral%d' % ephemeral_idx)
            ephemeral_idx += 1

    nics = boto.ec2.networkinterface.NetworkInterfaceCollection()
    nics.append(boto.ec2.networkinterface.NetworkInterfaceSpecification(
        subnet_id=subnet,
        groups=security_group_ids,
        associate_public_ip_address=assign_public_ip))

    ec2 = boto.ec2.connect_to_region(env.ec2_region)
    sirs = ec2.request_spot_instances(
        price=bid,
        image_id=ami,
        count=count,
        type='one-time',
        key_name=env.ec2_key_pair_name,
        instance_type=instance_type,
        monitoring_enabled=True,
        placement_group=placement_group,
        block_device_map=bdm,
        network_interfaces=nics)

    instance_ids = set()
    while True:
        time.sleep(10)
        done = True
        for sir in ec2.get_all_spot_instance_requests(map(lambda x: x.id, sirs)):
            print 'State:  %s' % sir.state
            print 'Fault:  %s' % sir.fault
            print 'Status: %s' % sir.status.message
            if sir.state not in ('open', 'active'):
                abort('Failed to launch instances')
            if sir.state == 'open':
                done = False
            if sir.state == 'active':
                instance_ids.add(sir.instance_id)

        if done:
            break

    for instance_id in instance_ids:
        ec2.modify_instance_attribute(
            instance_id=instance_id,
            attribute='sourceDestCheck',
            value=source_dest_check)

    print ''
    print 'Instances:'
    for reservation in ec2.get_all_instances(list(instance_ids)):
        for instance in reservation.instances:
            if tags is not None:
                instance.add_tags(tags)

            print '    %s' % instance.id
            print '        type:        %s' % instance.instance_type
            print '        internal ip: %s' % instance.private_ip_address
            print '        public ip:   %s' % instance.ip_address
            print '        tags:'
            for tag, value in sorted(instance.tags.iteritems(), lambda a, b: cmp(a[0], b[0])):
                print '            %s: %s' % (tag, value)
Example #7
0
        key_name='east_keypair',
        instance_type='t2.micro',
        security_group_ids=[sg_public.id],
        subnet_id=pubsub.id)

inst = reservation.instances[0]
inst.add_tag("Name","NAT Instance by Python")
print "Tagged the instance!"


while inst.state == 'pending':
	time.sleep(5)
	inst.update()

#Change the attribute for NAT'ing
ec2.modify_instance_attribute(inst.id, attribute='sourceDestCheck', value=False)
print "Attribute changed!"

#Assign elastic IP 54.173.234.49 to the NAT Instance
eip = ec2.allocate_address(None, False)
eip.associate(inst.id,None, None,False,False)


#========================================================================

#========================================================================
# Create the Private Instance
ec2 = boto.ec2.connect_to_region('us-east-1')
reservation = ec2.run_instances(
        'ami-b66ed3de',
        key_name='east_keypair',
    if not instances:
        module.fail_json(msg="Could not find instance with id '{}'".format(instance_id))

    instance = instances[0]

    groups = instance.groups
    group_ids = [gr.id for gr in groups]

    if group_id in group_ids:
        module.exit_json(changed=False)
        return

    group_ids.append(group_id)

    try:
        return ec2.modify_instance_attribute(instance_id, 'groupSet', group_ids)
    except boto.exception.EC2ResponseError, e:
        module.fail_json(msg=str(e))


def de_assign_group(ec2, module, instance_id, group_id):
    # retrieve instance
    try:
        instances = ec2.get_only_instances(instance_ids=[instance_id])
    except boto.exception.EC2ResponseError, e:
        module.fail_json(msg=str(e))

    if not instances:
        module.fail_json(msg="Could not find instance with id '{}'".format(instance_id))

    instance = instances[0]
Example #9
0
    changed = False

    try:
        instance.update()
        dot = instance.block_device_mapping[device_name].delete_on_termination
    except boto.exception.BotoServerError, e:
        module.fail_json(msg="%s: %s" % (e.error_code, e.error_message))

    if delete_on_termination != dot:
        try:
            bdt = BlockDeviceType(delete_on_termination=delete_on_termination)
            bdm = BlockDeviceMapping()
            bdm[device_name] = bdt

            ec2.modify_instance_attribute(instance_id=instance.id,
                                          attribute='blockDeviceMapping',
                                          value=bdm)

            while instance.block_device_mapping[
                    device_name].delete_on_termination != delete_on_termination:
                time.sleep(3)
                instance.update()
            changed = True
        except boto.exception.BotoServerError, e:
            module.fail_json(msg="%s: %s" % (e.error_code, e.error_message))

    return changed


def detach_volume(module, ec2, volume):