Boto3 get EC2 instance's volume

前端 未结 5 562
既然无缘
既然无缘 2021-01-14 10:00

I am trying to get volume-id list of aws instance using boto 3, I am getting sort of collection manager but I don\'t know how to get the data inside.

import          


        
相关标签:
5条回答
  • 2021-01-14 10:11

    e.g. you can get the volume ID and size simply by iterating over it.

    for volume in volumes:
        print (volume.id, volume.size)
    
    0 讨论(0)
  • 2021-01-14 10:15

    You can use cli also. Example I'm trying to get list of root volumes attached

    aws ec2 describe-volumes --filters "Name=attachment.device,Values=*sda1" --query "Volumes[*].[VolumeId]"  --output text --profile=my_genius_aws_profile
    
    0 讨论(0)
  • 2021-01-14 10:16

    It's just an iterable of objects so

    for v in volumes:
        print(v.id)
    

    if you want to get a list of id :

    l = [v.id for v in volumes]
    
    0 讨论(0)
  • 2021-01-14 10:24

    Using an EC2 client:

    ec2_client = boto3.client('ec2',
                        aws_access_key_id='XYZ',
                        aws_secret_access_key='XYZ',
                        region_name='us-east-1')
    volumes = ec2_client.describe_instance_attribute(InstanceId='i-0b30bea4e05579def',
    Attribute='blockDeviceMapping')
    
    0 讨论(0)
  • 2021-01-14 10:32

    An iterator is returned by ec2.Instance.volumesCollection

    You can extract the volume ids with code like this

    volume_id_list=[]
    for item in instance.volumes.all():
      volume_id_list.append(item.id)
    

    then volume_id_list[0] contains the first disk, volume_id_list[1] the second etc

    See https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Instance.volumes

    0 讨论(0)
提交回复
热议问题