Karthikraj
Karthikraj

Reputation: 7

Get values from JSON in Ruby

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
    }, 
 ]
}

Upvotes: 0

Views: 137

Answers (1)

shubhamgupta0122
shubhamgupta0122

Reputation: 48

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

Upvotes: 2

Related Questions