从停止的实例中分离磁盘

Detaching disk from stopped instance

我正在尝试从当前持有磁盘的已停止实例分离磁盘。这是我目前的做法。

def detach_disk_from_instance(disk_name, zone=GCLOUD_ZONE):
    disk_info = get_disk_info(disk_name=disk_name, zone=zone)
    if disk_info.get('users'):
        instance_name = disk_info['users'][0].rsplit('/').pop()
        logger.info("detatching disk : {} from instance : {}".format(disk_name, instance_name))
        request = compute.instances().detachDisk(
            project=GCLOUD_PROJECT_NAME, zone=zone, instance=instance_name, deviceName=disk_name)
        return make_http_request(request, {})

def wait_for_operation(operation, zone=GCLOUD_ZONE, worker=1):
    logger.info('Waiting for operation {} to finish...'.format(operation))
    with ThreadPoolExecutor(worker) as executor:
        future = executor.submit(_check_operation_status, operation=operation, zone=zone)
        wait([future])
        return future.result()

req = detach_disk_from_instance(disk_name='test-disk')
wait_for_operation(operation=req['name'])

如果持有磁盘的实例当前为 运行,则以上代码有效。 但如果实例停止,它就不起作用。当我尝试从已停止的实例中分离磁盘时出现以下错误。

{'errors': [{'message': "No attached disk found with device name 'test-disk'", 'code': 'INVALID_USAGE'}]}

我向您保证,磁盘仍连接到实例,gcp 仪表板也显示了这一点。

TL;DR - 您传递的是磁盘资源的 name 而不是磁盘附加到实例的 device name .

在请求的 instances.attachDisk request to attach a disk to a VM instance you can specify the device name in the deviceName 字段中。

deviceName

string

Specifies a unique device name of your choice that is reflected into the /dev/disk/by-id/google-* tree of a Linux operating system running within the instance. This name can be used to reference the device for mounting, resizing, and so on, from within the instance.

If not specified, the server chooses a default device name to apply to this disk, in the form persistent-disks-x, where x is a number assigned by Google Compute Engine. This field is only applicable for persistent disks.

您需要将此名称用作 instances.detachDisk 请求的 deviceName 查询参数。

Required query parameters

deviceName

string

Disk device name to detach.

如文档中所述,如果您在附加磁盘时未指定设备名称,GCE 会生成一个格式为 persistent-disks-x 的设备名称,您必须指定此名称。