草庐IT

关于亚马逊网络服务:AWS EBS Volume – Python – 查找所有字段信息,如 AWS EC2 EBS Volume Console 中所示

codeneng 2023-03-28 原文

AWS EBS Volume - Python - Find all fields info as shown in AWS EC2 EBS Volume Console

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

1
2
3
4
5
6
7
8
9
10
11
[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().

时从未将其纳入其值

1
2
3
4
5
6
[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 awspython -m pip install awspip install aws,或者运行了脚本(仅在 #Import classes from aws package 行之后包含行,在他的存储库的 aws 文件夹内(克隆后),但仍然出现错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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 错误是:

1
2
3
4
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,那么我会得到:

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

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

  • 似乎很接近,我试过这个 import boto3 ec2 = boto3.resource('ec2', region_name="us-west-2") volumes = ec2.volumes.all() for vol in volumes: for inst_vol in ec2.Volume(vol.id): print"--" + str(inst_vol.volume_type) 但它仍然出错。戳进去。
  • 这行得通: volume = ec2.Volume('vol-b4e1fabc') print volume.volume_type 但是,我想知道为什么当我在上面使用 2 for 循环时它不起作用。第一个 for 循环会将有效的卷 ID vol-xxxxx 传递给 ec2.Volume(<here>),但它因以下错误而哭泣:for inst_vol in ec2.Volume(vol.id): TypeError: 'ec2.Volume' object is not iterable。 `
  • 因为 ec2.Volume 不是 list 而是一个类。你不能遍历它。您上面的原始打印语句现在可以使用:print"Created(" + str(vol.create_time) +"),VolumeState(" + str(vol.state) +"),VolumeID(" + str(vol.id) +"),VolumeSize(" + str(vol.size) +")" + vol.volume_type
  • 没关系,谢谢它现在起作用了。我不必使用第二个 for 循环。仍在检查是否会根据 AWS 控制台为我提供所有字段。


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 插件 - aws ec2 ebs volumen info - 度量解析错误,原因:[缺少字段] 或遇到的错误:[无效数字]

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

有关关于亚马逊网络服务:AWS EBS Volume – Python – 查找所有字段信息,如 AWS EC2 EBS Volume Console 中所示的更多相关文章

  1. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  4. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  5. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  6. ruby-on-rails - 启动 Rails 服务器时 ImageMagick 的警告 - 2

    最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru

  7. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  8. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  9. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  10. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

随机推荐