简体   繁体   English

在 Boto 中列出 EC2 卷

[英]List EC2 volumes in Boto

I want to list all volumes attached to my EC2 instance.我想列出附加到我的 EC2 实例的所有卷。

I can list volumes with my code:我可以用我的代码列出卷:

conn = EC2Connection()
attribute = get_instance_metadata()
region=attribute['local-hostname'].split('.')[1]
inst_id = attribute['instance-id']
aws = boto.ec2.connect_to_region(region)
volume=attribute['local-hostname']
volumes = str(aws.get_all_volumes(filters={'attachment.instance-id': inst_id}))

But this results in:但这导致:

[vol-35b0b5fa, Volume:vol-6cbbbea3]

I need something like:我需要这样的东西:

vol-35b0b5fa
vol-6cbbbea3

If you are using Boto3 library then here is the command to list out all attached volumes如果您使用的是 Boto3 库,那么这里是列出所有附加卷的命令

import boto3
ec2 = boto3.resource('ec2', region_name='us-west-2')
volumes = ec2.volumes.all() # If you want to list out all volumes
volumes = ec2.volumes.filter(Filters=[{'Name': 'status', 'Values': ['in-use']}]) # if you want to list out only attached volumes
[volume for volume in volumes]

The get_all_volumes call in boto returns a list of Volume objects. boto 中的get_all_volumes调用返回一个Volume对象列表。 If all you need is the ID of the volume, you can get that using the id attribute of the Volume object:如果您只需要卷的 ID,则可以使用Volume对象的id属性获取它:

import boto.ec2
ec2 = boto.ec2.connect_to_region(region_name)
volumes = ec2.get_all_volumes()
volume_ids = [v.id for v in volumes]

The variable volume_ids would now be a list of strings where each string is the ID of one of the volumes.变量volume_ids现在将是一个字符串列表,其中每个字符串是其中一个卷的 ID。

I think here the requirement is just to iterate over the list with v.id: Just add this to your code:我认为这里的要求只是用 v.id 遍历列表:只需将其添加到您的代码中:

for v in volumes:
    print v.id

A simple way to retrieve volumes would be as follows检索卷的简单方法如下

ec2 = boto3.resource('ec2',"us-west-1")
volume = ec2.volumes.all()
for vol in volume:
    print(vol.id)
    print(vol.tags)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM