gpt4 book ai didi

python - 如何从 key BlockDeviceMappings 获取 VolumeId(boto3 获取 ec2 的卷信息)

转载 作者:太空宇宙 更新时间:2023-11-03 14:00:50 28 4
gpt4 key购买 nike

由于以下原因,我想将 VolumeId 的值保存在变量中:

#!/usr/bin/env python
import boto3
import json
import argparse
import logging
import pprint
parser = argparse.ArgumentParser(
description='get_ec2_inst_state'
)
parser.add_argument("-v", "--verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
logging.debug('running debug mode')

ec2client = boto3.client('ec2')
instance_id_value = input("Please enter the ec2 instance id : ")
volume = ec2client.describe_instance_attribute(InstanceId= instance_id_value,Attribute='blockDeviceMapping')
#for key in volume:
# print (key)
#print (volume)
#pprint.pprint(volume, width=1)
for key,value in volume.items():
print(key,value)
#for key,value in value.items():
# print(key, ":", value)

结果:./get_ec2_inst_vol.py

Please enter the ec2 instance id : i-09f9696ce9150eb1f
BlockDeviceMappings [{'DeviceName': '/dev/sda1', 'Ebs': {'AttachTime': datetime.datetime(2018, 1, 29, 1, 0, 52, tzinfo=tzlocal()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-0b42c57c7ba0281d6'}}]
InstanceId i-09f9696ce9150eb1f
ResponseMetadata {'RequestId': '6c4bbe79-5583-4ee4-8131-1e3bde5e4fa9', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type': 'text/xml;charset=UTF-8', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'date': 'Tue, 13 Mar 2018 11:51:45 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}

现在,我如何从关键的 BlockDeviceMappings 中获取 VolumeId 。请记住,卷对象是字典类型

-------------------- 注释 -------------------------- --使用资源接口(interface)VS客户端,部分链接:

  1. When to use a boto3 client and when to use a boto3 resource?
  2. http://boto3.readthedocs.io/en/latest/guide/resources.html
  3. http://boto3.readthedocs.io/en/latest/guide/clients.html

最佳答案

boto3 有一个很棒的功能 called Service Resource 。实例类型子资源具有 attribute block_device_mappings 。利用它:

ec2 = boto3.resource('ec2')
instance = ec2.Instance(instance_id)
for device in instance.block_device_mappings:
volume = device.get('Ebs')
print(volume.get('VolumeId'))

关于python - 如何从 key BlockDeviceMappings 获取 VolumeId(boto3 获取 ec2 的卷信息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49255529/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com