how to get volume id attached to instance from AWS CLI

i want to get volume id attached to instance like how we get instance id from the meta data

InstanceID=`curl http://169.254.169.254/latest/meta-data/instance-id

Solution 1:

The volumes IDs are not available from the metadata. The virtual devices are available under block-device-mapping/

You will need to use the AWS CLI (or script, program, etc.) to get the volume IDs assigned to an instance.

With the CLI:

aws ec2 describe-volumes

The output will include the instance ID that a volume is attached to.

Once you know the instance ID, you can filter on just those volumes attached to that instance:

aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=i-555550604eaf99999

The documentation will have more details and examples.

describe-volumes

Solution 2:

The answer is already given but I was looking for current instance attach volume from which I am running query.

So you can just pass the instance Id from the curl response.

aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)

sample output

{
    "Volumes": [
        {
            "AvailabilityZone": "us-west-2b", 
            "Attachments": [
                {
                    "AttachTime": "2018-03-01T07:47:43.000Z", 
                    "InstanceId": "i-abcdedf", 
                    "VolumeId": "vol-12345", 
                    "State": "attached", 
                    "DeleteOnTermination": true, 
                    "Device": "/dev/xvda"
                }
            ], 
            "Encrypted": false, 
            "VolumeType": "gp2", 
            "VolumeId": "vol-123456", 
            "State": "in-use", 
            "Iops": 450, 
            "SnapshotId": "snap-1234", 
            "CreateTime": "2018-03-01T07:47:43.261Z", 
            "Size": 150
        }
    ]
}