0

I am trying to get the VolumeId and State of the Volume attached to the machines using aws API .

Code

#!/usr/local/bin/ruby
require "aws-sdk"
require "rubygems"


list=Aws::EC2::Client.new(region: "us-east-1")
volume=list.describe_volumes()
volumes=%x( aws ec2 describe-volumes --region='us-east-1' )
puts volumes

Below is the sample output of the command aws ec2 describe-volumes --region='us-east-1' . Please help to get VolumeID and state from the below

Sample Output of API(JSON):

{
"Volumes": [
    {
        "AvailabilityZone": "us-east-1d", 
        "Attachments": [
            {
                "AttachTime": "2015-02-02T07:31:36.000Z", 
                "InstanceId": "i-bca66353", 
                "VolumeId": "vol-892a2acd", 
                "State": "attached", 
                "DeleteOnTermination": true, 
                "Device": "/dev/sda1"
            }
        ], 
        "Encrypted": false, 
        "VolumeType": "gp2", 
        "VolumeId": "vol-892a2acd", 
        "State": "in-use", 
        "Iops": 100, 
        "SnapshotId": "snap-df910966", 
        "CreateTime": "2015-02-02T07:31:36.380Z", 
        "Size": 8
    }, 
 ]
}
1
  • 2
    If the output you receive is valid json, you should be able to do JSON.parse(volumes)['Volumes'].map {|volume| volume["VolumeId"] } to get an array of volume idw. Commented Sep 18, 2018 at 8:38

1 Answer 1

2

for getting just the volume_ids ->

JSON.parse(volumes)['Volumes'].map{|v|v["VolumeId"]}

for getting just the states ->

JSON.parse(volumes)['Volumes'].map{|v|v["state"]}

for getting a hash/map with volume-ids as keys and their states as values ->

JSON.parse(volumes)['Volumes'].map{|v| [v["VolumeId"],v["state"]] }.to_h
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.