使用Boto查找挂载到哪个设备和EBS卷
我怎么用Python的Boto库找到一个EBS卷挂载在哪个设备上,版本是v2.0?
boto.ec2.Volume里有一些有趣的属性,比如attachment_state
和volume_state
。不过有没有什么函数可以用来查看设备映射呢?
boto.manage.volume里有get_device(self, params)
这个方法,但它需要一个CommandLineGetter。
有没有什么建议或者使用boto.manage
的示例?
4 个回答
2
如果你还想获取块设备的映射信息(在Linux中,就是EBS卷的本地设备名称),你可以使用 EC2Connection.get_instance_attribute
来获取本地设备名称和它们对应的EBS对象的列表:
def get_block_device_mapping(instance_id):
return conn.get_instance_attribute(
instance_id=instance_id,
attribute='blockDeviceMapping'
)['blockDeviceMapping']
这个方法会返回一个字典,字典的键是本地设备名称,值是对应的EBS对象(通过这些对象你可以获取很多信息,比如卷的ID)。
9
不太清楚你是在实例内部运行这个还是在外部运行。如果是在外部运行的话,你就不需要调用元数据了,只需要提供实例的ID就可以了。
from boto.ec2.connection import EC2Connection
from boto.utils import get_instance_metadata
conn = EC2Connection()
m = get_instance_metadata()
volumes = [v for v in conn.get_all_volumes() if v.attach_data.instance_id == m['instance-id']]
print(volumes[0].attach_data.device)
要注意的是,一个实例可能有多个存储卷,所以写代码的时候要考虑到可能不止一个设备,而不是假设只有一个。
12
我觉得你要找的就是attach_data.device,它是卷的一部分。
这里有个例子,虽然我不确定这是不是最好的方法,但它会输出一些信息,比如volumeid、instanceid和attachment_data,类似于下面这样:
Attached Volume ID - Instance ID - Device Name
vol-12345678 - i-ab345678 - /dev/sdp
vol-12345678 - i-ab345678 - /dev/sda1
vol-12345678 - i-cd345678 - /dev/sda1
import boto
ec2 = boto.connect_ec2()
res = ec2.get_all_instances()
instances = [i for r in res for i in r.instances]
vol = ec2.get_all_volumes()
def attachedvolumes():
print 'Attached Volume ID - Instance ID','-','Device Name'
for volumes in vol:
if volumes.attachment_state() == 'attached':
filter = {'block-device-mapping.volume-id':volumes.id}
volumesinstance = ec2.get_all_instances(filters=filter)
ids = [z for k in volumesinstance for z in k.instances]
for s in ids:
print volumes.id,'-',s.id,'-',volumes.attach_data.device
# Get a list of unattached volumes
def unattachedvolumes():
for unattachedvol in vol:
state = unattachedvol.attachment_state()
if state == None:
print unattachedvol.id, state
attachedvolumes()
unattachedvolumes()