【发布时间】:2017-07-24 14:36:21
【问题描述】:
我正在尝试创建一个 Python 脚本来针对所有可用的 AWS EBS 卷生成一个csv 格式文件,并显示我在 AWS EC2 EBS 卷控制台中看到的所有字段值。
[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 字段,则上述脚本有效。它不起作用,因为 volumes 变量在运行 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 卷控制台中看到的),请参见下图AWS 控制台中的可用字段。
我在Github 上在线找到了这个其他脚本(#2),它似乎可以打印更多字段,但它给出了下面列出的另一个错误。我成功运行了python -m pip install --user aws 或python -m pip install aws 或pip install aws,或运行了脚本(仅包含#Import classes from aws package line 之后的行,在他的存储库的aws 文件夹内(克隆后)但仍然得到错误。
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
【问题讨论】:
标签: python amazon-web-services amazon-ec2 boto boto3