'Rebuild the given instance with the provided attributes.'

@check_instance_lock
@check_instance_cell
@check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED, vm_states.ERROR])
def rebuild(self, context, instance, image_href, admin_password, files_to_inject=None, **kwargs):

    orig_image_ref = (instance.image_ref or '')
    files_to_inject = (files_to_inject or [])
    metadata = kwargs.get('metadata', {})
    preserve_ephemeral = kwargs.get('preserve_ephemeral', False)
    auto_disk_config = kwargs.get('auto_disk_config')
    (image_id, image) = self._get_image(context, image_href)
    self._check_auto_disk_config(image=image, **kwargs)
    flavor = instance.get_flavor()
    root_bdm = compute_utils.get_root_bdm(context, instance)
    self._checks_for_create_and_rebuild(context, image_id, image, flavor, metadata, files_to_inject, root_bdm)
    (kernel_id, ramdisk_id) = self._handle_kernel_and_ramdisk(context, None, None, image)
    def _reset_image_metadata():
        "Remove    old    image    properties    that    we're    storing    as    instance\n                                                system    metadata.        These    properties    start    with    'image_'.\n                                                Then    add    the    properties    for    the    new    image.\n                                                "
        orig_sys_metadata = dict(instance.system_metadata)
        for key in list(instance.system_metadata.keys()):
            if key.startswith(utils.SM_IMAGE_PROP_PREFIX):
                del instance.system_metadata[key]
        new_sys_metadata = utils.get_system_metadata_from_image(image, flavor)
        instance.system_metadata.update(new_sys_metadata)
        instance.save()
        return orig_sys_metadata
    options_from_image = self._inherit_properties_from_image(image, auto_disk_config)
    instance.update(options_from_image)
    instance.task_state = task_states.REBUILDING
    instance.image_ref = image_href
    instance.kernel_id = (kernel_id or '')
    instance.ramdisk_id = (ramdisk_id or '')
    instance.progress = 0
    instance.update(kwargs)
    instance.save(expected_task_state=[None])
    orig_sys_metadata = _reset_image_metadata()
    bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(context, instance.uuid)
    self._record_action_start(context, instance, instance_actions.REBUILD)
    try:
        request_spec = objects.RequestSpec.get_by_instance_uuid(context, instance.uuid)
    except exception.RequestSpecNotFound:
        request_spec = None
    self.compute_task_api.rebuild_instance(context, instance=instance, new_pass=admin_password, injected_files=files_to_inject, image_ref=image_href, orig_image_ref=orig_image_ref, orig_sys_metadata=orig_sys_metadata, bdms=bdms, preserve_ephemeral=preserve_ephemeral, host=instance.host, request_spec=request_spec, kwargs=kwargs)
