如何通过pyVmomi获取VMware vSphere中虚拟机虚拟磁盘的存储策略?
回答:直接从VirtualDisk获取存储策略,无需反向推导
Good news—you don't need to jump through hoops with datastores to get storage policy info! You can access it directly from the VirtualDisk objects you're already looping through in your pyVmomi code.
具体实现方法
Here's how to extend your existing loop to pull storage policy details seamlessly:
# 假设你已经获取了virtual_machine对象和服务实例的content对象 for device in virtual_machine.config.hardware.device: if isinstance(device, vim.vm.device.VirtualDisk): # 直接获取磁盘关联的存储策略对象 disk_storage_policy = device.storagePolicy if disk_storage_policy: # 提取策略的唯一ID policy_id = disk_storage_policy.policyId # 如果需要策略名称、规则等详细信息,通过StoragePolicyManager查询 storage_policy_manager = content.virtualCenterStoragePolicyManager policy_details = storage_policy_manager.PolicyRetrieve(content, policy_id) # 输出磁盘和策略信息 print(f"磁盘: {device.deviceInfo.label} (容量: {device.capacityInKB/1024/1024:.2f} GB)") print(f" 存储策略名称: {policy_details.name}") print(f" 存储策略ID: {policy_id}") else: print(f"磁盘: {device.deviceInfo.label} 未配置任何存储策略")
关键细节说明
- 直接访问属性: The
VirtualDiskclass in pyVmomi includes a nativestoragePolicyattribute that directly references the policy assigned to that disk. No messy datastore queries or mapping required—this is the cleanest, most direct path. - 策略详细信息: The
storagePolicyattribute gives you the policy ID out of the box. If you need human-readable names or specific policy rules, use theVirtualCenterStoragePolicyManagerto fetch full details using the policy ID. - 兼容性: This method works on vSphere 6.0 and later, which covers nearly all modern production environments. If you're stuck on an extremely old vSphere version, you might need fallback logic, but that's a rare edge case.
为什么反向推导不是好选择?
Reverse-engineering from datastores would be inefficient and error-prone: multiple disks could share the same datastore but use different policies, or a single policy could span multiple datastores. Directly accessing the disk's storagePolicy attribute avoids all those headaches.
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

