AWS EBS卷 - Python - 查找AWS EC2 EBS Volume Console中显示的所有字段信息

时间:2017-03-04 13:28:06

标签: python amazon-web-services amazon-ec2 boto boto3

我尝试创建一个Python脚本,针对所有可用的AWS EBS卷生成csv格式文件,并显示我在AWS EC2 EBS Volume Console中看到的所有字段值。

[arun@Andrews-MBP-2 ~/aks/always-latest-ws-sunny/anisble] $ cat ~/aws-vol-info.py 
import boto3

#define the connection
ec2 = boto3.resource('ec2', region_name="us-west-2")

volumes = ec2.volumes.all()

for vol in volumes:
    print "Created(" + str(vol.create_time) + "),VolumeState(" + str(vol.state) + "),VolumeID(" + str(vol.id) + "),VolumeSize(" + str(vol.size) + ") " + vol.type
[arun@Andrews-MBP-2 ~/aks/always-latest-ws-sunny/anisble] $ 

此脚本给出了以下错误消息。原因:如果我不使用vol.type字段,则上述脚本有效。它没有工作,因为变量在运行ec2.volumes.all()时从来没有得到它的价值。

[arun@Andrews-MBP-2 ~/aks/always-latest-ws-sunny/anisble] $ python ~/aws-vol-info.py 
Traceback (most recent call last):
  File "/Users/arun/aws-vol-info.py", line 9, in <module>
    print "Created(" + str(vol.create_time) + "),VolumeState(" + str(vol.state) + "),VolumeID(" + str(vol.id) + "),VolumeSize(" + str(vol.size) + ") " + vol.type
AttributeError: 'ec2.Volume' object has no attribute 'type'
[arun@Andrews-MBP-2 ~/aks/always-latest-ws-sunny/anisble] $ 

我应该在上面的脚本中使用/更改哪些库/功能,我可以使用它来显示EBS卷的所有字段或更有意义的字段(我在AWS EC2 EBS Volume控制台中看到的内容),请参见下面的图片AWS Console中的可用字段。

enter image description here

我在Github上发现了这个其他脚本(#2),这似乎可以打印更多字段,但它会给出下面列出的其他错误。我成功运行了python -m pip install --user awspython -m pip install awspip install aws,或者在#Import classes from aws package文件夹中运行了脚本(仅在aws line之后包含行根据他的存储库(克隆后)但仍然收到错误。

import boto.ec2
class Volumes:
    def __init__(self):
        ''' Volumes Constructor '''

    def list_volumes(conn):
        ''' List Volumes '''
        # get all volumes
        vols = conn.get_all_volumes()

        # if volumes found
        if vols:
            #loop through volumes
            for v in vols:
                print 'Volume Id:', v.id
                print 'Volume Status:', v.status
                print 'Volume Size:', v.size
                print 'Zone:', v.zone
                print 'Volume Type:', v.type
                print 'Encrypted:', v.encrypted

                #print attachment set object
                attachmentData = v.attach_data
                print 'Instance Id:', attachmentData.instance_id
                print 'Attached Time:', attachmentData.attach_time
                print 'Device:', attachmentData.device
                print '**********************************'

#Import classes from aws package
from aws import Connection
from aws import EC2Instance
from aws import Volumes
#import aws

connInst = Connection()
conn = connInst.ec2Connection()

#instantiate Volumes and list volumes
volumeInst = Volumes()
volumeInst.list_volumes(conn)

脚本#2错误是:

Traceback (most recent call last):
  File "/Users/arun/aws-vol-info2.py", line 30, in <module>
    from aws import Connection
ImportError: cannot import name Connection

如果我在脚本#2中注释from aws ... ..并且只使用/取消注释import aws,那么我就是这样:

Traceback (most recent call last):
  File "/Users/arun/aws-vol-info2.py", line 35, in <module>
    connInst = Connection()
NameError: name 'Connection' is not defined

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找vol.volume_type。您可以在此处查看ec2.Volume中的完整属性列表: http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#volume

答案 1 :(得分:0)

可以增强此脚本以显示更有意义的信息,但使用 jpavs 中的提示,我想出了这个脚本~/aws-vol-info.py

import boto3

# Define the connection
ec2 = boto3.resource('ec2', region_name="us-west-2")

# Find all volumes
volumes = ec2.volumes.all()

# Loop through all volumes and pass it to ec2.Volume('xxx')
for vol in volumes:
    iv = ec2.Volume(str(vol.id))
    print "Created(" + str(iv.create_time) + "),AZ(" + str(iv.availability_zone) + "),VolumeID(" + str(iv.volume_id) + "),VolumeType(" + str(iv.volume_type) + "),State(" + str(iv.state) + "),Size(" + str(iv.size) + "),IOPS(" + str(iv.iops) + "),IsEncrypted(" + str(iv.encrypted) + "),SnapshotID(" + str(iv.snapshot_id) + "),KMS_KEYID(" + str(iv.kms_key_id) + ")",

    # The following next 2 print statements variables apply only in my case.
    print ",InstanceID(" + str(iv.attachments[0]['InstanceId']) + "),InstanceVolumeState(" + str(iv.attachments[0]['State']) + "),DeleteOnTerminationProtection(" + str(iv.attachments[0]['DeleteOnTermination']) + "),Device(" + str(iv.attachments[0]['Device']) + ")",
    if iv.tags:
        print ",Name(" + str(iv.tags[0]['Name']) + "),Mirror(" + str(iv.tags[0]['mirror']) + "),Role(" + str(iv.tags[0]['role']) + "),Cluster(" + str(iv.tags[0]['cluster']) + "),Hostname(" + str(iv.tags[0]['hostname']) + "),Generation(" + str(iv.tags[0]['generation']) + "),Index(" + str(iv.tags[0]['index']) + ")"
    print ""

Ran: python ~/aws-vol-info.py它为我提供了python脚本中提到的所有字段的CSV格式值。很少(2-3)AWS控制台字段丢失,因为库没有提供这些字段,但无论我从上面得到什么,或者如果我深入研究iv.attachments[0]['<somekey>']iv.tags[0]['<somekey>']对我来说都足够了这一次。

PS iv.attachmentsiv.tags都是iv对象中的列表/字典类型变量,因此您可以通过显示具体内容来增强脚本想从中获取。因此,如果你想要InstanceID,那么你可以使用它:str(iv.attachments[0]['InstanceId'])来打印它。

要获得更好的版本:请在此处查看.python脚本:telegraf - exec plugin - aws ec2 ebs volumen info - metric parsing error, reason: [missing fields] or Errors encountered: [ invalid number]

此处也找到了这个有用的脚本:http://www.n2ws.com/blog/ebs-report.html