Пример #1
0
def get_base_ec2_instance(conn, base_ec2_name=None, base_ec2_id=None):
    """
    Get EC2 instance by Name tag or instance id.
    :param conn: EC2 connection
    :type conn: boto.ec2.EC2Connection
    :param base_ec2_name: Name tag of based ec2 instance
    :type base_ec2_name: str
    :param base_ec2_id: Instance id of based ec2 instance
    :type base_ec2_id: str
    :rtype: list
    :return: EC2 Instance
    """

    if not base_ec2_name and not base_ec2_id:
        raise EC2MoreLikeThisException(
            '"base_ec2_name" or "base_ec2_id" argument is required.')
    elif base_ec2_name and base_ec2_id:
        raise EC2MoreLikeThisException(
            '"base_ec2_name" and "base_ec2_id" arguments are exclusive.')
    elif base_ec2_name:
        logging.debug('Use "Name" tag to searching based EC2 instance.')
        try:
            reservations = conn.get_all_instances(
                filters={'tag:Name': base_ec2_name})
            instances = reservations[0].instances
            if len(instances) > 1:
                raise EC2MoreLikeThisException(
                    'Found more then two instances...')
            elif len(instances) <= 0:
                raise EC2MoreLikeThisException(
                    'Instance which has "{0}" as "Name" tag does not exist...'
                    ''.format(base_ec2_name))
            logging.debug('Base instance is {0}.'.format(instances))
            return instances[0]
        except boto.exception.EC2ResponseError as exception:
            raise EC2MoreLikeThisException(exception.__str__())
    elif base_ec2_id:
        logging.debug('Use "InstanceId" tag to searching based EC2 instance.')
        try:
            reservations = conn.get_all_instances(instance_ids=[base_ec2_id])
            instances = reservations[0].instances
            if len(instances) <= 0:
                raise EC2MoreLikeThisException(
                    'Instance ID: {0} does not exist...'.format(base_ec2_id))
            logging.debug('Base instance is {0}.'.format(instances))
            return instances[0]
        except boto.exception.EC2ResponseError as exception:
            raise EC2MoreLikeThisException(exception.__str__())
Пример #2
0
    def post(self):
        try:
            remote_ip = get_remote_ip(request_obj=self.request)
            if remote_ip is None:
                self.set_status(httplib.INTERNAL_SERVER_ERROR)
                self.finish({
                    'status_code': self.get_status(),
                    'message': 'Sorry, could not get Your IP Address.'
                })

            self.get_ec2_connection()
            authorize_ips(conn=self.conn,
                          remote_ip=remote_ip,
                          security_group_defines=self.security_group_defines)
            message = ('Your IP address {ip} is appended to {sg}.'
                       ''.format(ip=remote_ip,
                                 sg=self.security_group_defines.keys()))
            self.finish({'status_code': self.get_status(), 'message': message})

        except boto.exception.EC2ResponseError as exception:
            self.set_status(httplib.BAD_REQUEST)
            self.finish({
                'status_code': self.get_status(),
                'message': exception.error_message
            })

        except Exception as exception:
            self.set_status(httplib.INTERNAL_SERVER_ERROR)
            self.finish({
                'status_code': self.get_status(),
                'message': exception.__str__()
            })
Пример #3
0
    def add_name_tag_to_volume(self, instance_id, block_device_mapping):
        """
        Set Instance ID to tag of volume's Name.
        :param instance_id: Instance ID (Any string)
        :type instance_id: str
        :param block_device_mapping: Block device mapping of instance.
        :type block_device_mapping:
        boto.ec2.blockdevicemapping.BlockDeviceMapping
        :return: True
        :rtype: bool
        """

        instance_id = self.ec2_tags.get('Name', instance_id)

        for key, value in block_device_mapping.items():
            tag_value = ('{instance_id}:{device}'
                         ''.format(instance_id=instance_id, device=key))
            try:
                volumes = self.conn.get_all_volumes(
                    volume_ids=[value.volume_id])
                if len(volumes) > 0:
                    volume = volumes[0]
                    volume.add_tag(key='Name', value=tag_value)
                    logging.info('Add tag {{Name: {value}}} to {device}'
                                 ''.format(value=tag_value, device=key))
            except Exception as exception:
                raise EC2MoreLikeThisException(exception.__str__())

        return block_device_mapping
Пример #4
0
    def delete(self):
        try:
            self.get_ec2_connection()
            results = revoke_all_rules(
                conn=self.conn,
                security_group_ids=self.security_group_defines.keys()
            )
            self.finish(
                json.dumps({
                    'results': results
                })
            )

        except boto.exception.EC2ResponseError as exception:
            self.set_status(httplib.BAD_REQUEST)
            self.finish(
                {
                    'status_code': self.get_status(),
                    'message': exception.error_message
                }
            )

        except Exception as exception:
            self.set_status(httplib.INTERNAL_SERVER_ERROR)
            self.finish(
                {
                    'status_code': self.get_status(),
                    'message': exception.__str__()
                }
            )
Пример #5
0
def get_ami(conn, ami_id):

    try:
        result = conn.get_all_images(image_ids=[ami_id])
        logging.debug('Based "ami" is {0}'.format(result))
        return result[0]
    except boto.exception.EC2ResponseError as exception:
        raise EC2MoreLikeThisException(exception.__str__())
Пример #6
0
def create_conn(region_name, aws_access_key_id, aws_secret_access_key):

    try:
        conn = boto.ec2.connect_to_region(
            region_name=region_name,
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key)
    except Exception as exception:
        raise EC2MoreLikeThisException(exception.__str__())

    if conn is None:
        raise EC2MoreLikeThisException('Maybe failed to AWS authentication.')

    return conn
Пример #7
0
    def post(self):
        try:
            remote_ip = get_remote_ip(request_obj=self.request)
            if remote_ip is None:
                self.set_status(httplib.INTERNAL_SERVER_ERROR)
                self.finish(
                    {
                        'status_code': self.get_status(),
                        'message': 'Sorry, could not get Your IP Address.'
                    }
                )

            self.get_ec2_connection()
            authorize_ips(
                conn=self.conn,
                remote_ip=remote_ip,
                security_group_defines=self.security_group_defines
            )
            message = (
                'Your IP address {ip} is appended to {sg}.'
                ''.format(
                    ip=remote_ip,
                    sg=self.security_group_defines.keys()
                )
            )
            self.finish(
                {
                    'status_code': self.get_status(),
                    'message': message
                }
            )

        except boto.exception.EC2ResponseError as exception:
            self.set_status(httplib.BAD_REQUEST)
            self.finish(
                {
                    'status_code': self.get_status(),
                    'message': exception.error_message
                }
            )

        except Exception as exception:
            self.set_status(httplib.INTERNAL_SERVER_ERROR)
            self.finish(
                {
                    'status_code': self.get_status(),
                    'message': exception.__str__()
                }
            )
Пример #8
0
 def get(self):
     try:
         self.get_ec2_connection()
         parsed_security_groups = parse_security_groups(
             conn=self.conn,
             security_group_ids=self.security_group_defines.keys())
         self.finish(json.dumps(parsed_security_groups))
     except boto.exception.EC2ResponseError as exception:
         self.set_status(httplib.BAD_REQUEST)
         self.finish({
             'status_code': self.get_status(),
             'message': exception.error_message
         })
     except Exception as exception:
         self.set_status(httplib.INTERNAL_SERVER_ERROR)
         self.finish({
             'status_code': self.get_status(),
             'message': exception.__str__()
         })
Пример #9
0
    def delete(self):
        try:
            self.get_ec2_connection()
            results = revoke_all_rules(
                conn=self.conn,
                security_group_ids=self.security_group_defines.keys())
            self.finish(json.dumps({'results': results}))

        except boto.exception.EC2ResponseError as exception:
            self.set_status(httplib.BAD_REQUEST)
            self.finish({
                'status_code': self.get_status(),
                'message': exception.error_message
            })

        except Exception as exception:
            self.set_status(httplib.INTERNAL_SERVER_ERROR)
            self.finish({
                'status_code': self.get_status(),
                'message': exception.__str__()
            })
Пример #10
0
 def get(self):
     try:
         self.get_ec2_connection()
         parsed_security_groups = parse_security_groups(
             conn=self.conn,
             security_group_ids=self.security_group_defines.keys()
         )
         self.finish(json.dumps(parsed_security_groups))
     except boto.exception.EC2ResponseError as exception:
         self.set_status(httplib.BAD_REQUEST)
         self.finish(
             {
                 'status_code': self.get_status(),
                 'message': exception.error_message
             }
         )
     except Exception as exception:
         self.set_status(httplib.INTERNAL_SERVER_ERROR)
         self.finish(
             {
                 'status_code': self.get_status(),
                 'message': exception.__str__()
             }
         )
Пример #11
0
        more_like_this_ec2.apply_root_ebs_option(
            name='iops', value=options.override_root_ebs_iops)
    if options.override_optional_ebs_size:
        more_like_this_ec2.apply_optional_ebs_option(
            name='size',
            value=options.override_optional_ebs_size,
            device=options.override_optional_ebs_device)
    if options.override_optional_ebs_type:
        more_like_this_ec2.apply_optional_ebs_option(
            name='type',
            value=options.override_optional_ebs_type,
            device=options.override_optional_ebs_device)
    if options.override_optional_ebs_iops:
        more_like_this_ec2.apply_optional_ebs_option(
            name='iops',
            value=options.override_optional_ebs_iops,
            device=options.override_optional_ebs_device)

    more_like_this_ec2.run(wait_until_running=options.wait_until_running,
                           checking_state_term=10,
                           checking_count_threshold=60,
                           dry_run=options.dry_run)


if __name__ == '__main__':
    try:
        main()
    except EC2MoreLikeThisException as exception:
        logging.error(exception.__str__())
        sys.exit(1)