dimanche 23 août 2015

retrieve multiple values from json array using bash

I need to write a bash script to attach Amazon EBS volumes to a given instance based on the Name tag of the volume. The tag is in the format of "device on servername" e.g. "/dev/xvdf on linuxserver"

I can easily perform the following command to retrieve all the relevant instances, but I am having trouble iterating through each object in the json array to get VolumeId and Name tag.

aws ec2 describe-volumes --region $region --filter Name=tag-key,Values="Name" Name=tag-value,Values="*$servername" --filter Name="status",Values="available" | jq '.Volumes[]'

an example output is:

 [
  {
    "AvailabilityZone": "us-east-1d",
    "Attachments": [],
    "Tags": [
      {
        "Value": "/dev/xvdg on linuxserver",
        "Key": "Name"
      }
    ],
    "Encrypted": false,
    "VolumeType": "io1",
    "VolumeId": "vol-0233d8ec",
    "State": "available",
    "Iops": 120,
    "SnapshotId": "",
    "CreateTime": "2015-08-21T04:29:10.157Z",
    "Size": 4
  },
  {
    "AvailabilityZone": "us-east-1d",
    "Attachments": [],
    "Tags": [
      {
        "Value": "/dev/xvdf on linuxserver",
        "Key": "Name"
      }
    ],
    "Encrypted": false,
    "VolumeType": "io1",
    "VolumeId": "vol-433bc8ae",
    "State": "available",
    "Iops": 120,
    "SnapshotId": "",
    "CreateTime": "2015-08-21T04:28:23.819Z",
    "Size": 4
  }
]

Ideally, I'd like to do the following:

for object in $(aws ec2 describe-volumes --region $region --filter Name=tag-key,Values="Name" Name=tag-value,Values="*$servername" --filter Name="status",Values="available" | jq '.Volumes[]')
do
    echo $object.VolumeId
done 

But bash treats each line as an object in the array.

I'd be very appreciative of some suggestions on a better way to approach this.

Thanks




Aucun commentaire:

Enregistrer un commentaire