1

Hoping you can help with this query. Hopefully the answer should allow me to construct better queries down the line. I am trying to filter by the root device of a particular instance and get the root devices volume id. Could you explain how I could join two such queries. Searching for DeviceName /dev/sda1 and to then get the corresponding VolumeId.

aws ec2 describe-instances --instance-id i-02bc19e18ef09cdbe --query 'Reservations[].Instances[].BlockDeviceMappings[]'

[
    {
        "Ebs": {
            "AttachTime": "2017-04-20T13:32:04.000Z",
            "VolumeId": "vol-0118bd9c0a08164f2",
            "DeleteOnTermination": false,
            "Status": "attached"
        },
        "DeviceName": "/dev/sda1"
    }
]
the_frank
  • 55
  • 1
  • 1
  • 4
  • Have you tried `jq`? – chicks Apr 25 '17 at 21:13
  • Could you please clarify your requirement, or show some sample output? Do you want the `VolumeId` for `/dev/sda1` of multiple instances? – John Rotenstein Apr 26 '17 at 00:45
  • I would like the VolumeId for /dev/sda1, I am currently specifying a single instance I would assume however the filter/query is written could be applied to more than one instance. I have not tried jq, is this something that would be required? – the_frank Apr 26 '17 at 12:19

2 Answers2

2

This question is a little old, but here's a possible solution for you. Making one assumption - namely, that the root device is /dev/sda1. Which I think is a fairly good assumption for AWS. If you don't specify an instance-id, all of the instances will be returned. Then I'm doing a search of DeviceName equal to /dev/sda1. After the search term, a list is created with DeviceName and VolumeId.

aws ec2 describe-instances --query "Reservations[].Instances[].BlockDeviceMappings[?DeviceName == '/dev/sda1'].{DeviceName: DeviceName, VolumeID: Ebs.VolumeId}
oblio
  • 375
  • 1
  • 3
  • 12
LHWizard
  • 556
  • 4
  • 11
  • What if we don't want to assume /dev/sda1 and take the volume details from RootDeviceName? How will we construct the query? – Akash Kotian Feb 06 '19 at 13:11
1

I know it's late but still if anybody needs it, Here is the aws cli command which can be used to retrieve the root volume device name attached to an instance.

aws ec2 describe-instances --instance-ids <instance-id> --region <region-name> --query "Reservations[*].Instances[*].RootDeviceName" --output text

Using output of above command as the input to below command, we can retrieve the volume id..

aws ec2 describe-volumes  --region <region name> --filters Name=attachment.instance-id,Values=<instance-id> Name=attachment.device,Values=<output from above command> --query 'Volumes[*].VolumeId' --output text
Stuggi
  • 3,506
  • 4
  • 19
  • 36