Search code examples
shellamazon-web-servicesawkamazon-ec2amazon-ami

How to find ami id using shell script


How to find ami id using shell script

My Script :

for i in $(cat /tmp/amidel.txt); do
        echo "Image ID of instance which needed to be Deregistered is $i ";
        val1="$i"-i-*
        aws ec2 describe-images --filters "Name=name,Values=$val1" | awk '{ print  $11 }' 
done

Now Issue is that "aws ec2 describe-images" returns image id for different awk value :

$ aws ec2 describe-images --filters "Name=name,Values=instance-20Aug15-i-*" |  awk '{ print  $9 }'

Output :

ami-xxxx

$ aws ec2 describe-images --filters "Name=name,Values=instance-18Aug15-i-*" |  awk '{ print  $11 }' 

Output :

ami-xxxx

This is happening because third value returned by "aws ec2 describe-images" is Comment which varies for each ami image :

$ aws ec2 describe-images --filters "Name=name,Values=instance-18Aug15-i-*" 

Output :

IMAGES  x86_64  This is for Daily auto AMI creation xen ami-bebfb1ec    008392659736/instance-18Aug15-i-1effb6d3    machine aki-503e7402    instance-18Aug15-i-1effb6d3 008392659736    False   /dev/sda1   ebs available   paravirtual
BLOCKDEVICEMAPPINGS /dev/sda1
EBS True    snap-51539764   8   gp2
BLOCKDEVICEMAPPINGS /dev/sdf
EBS False   snap-4e95d37b   20  gp2

For 2nd Ami :

$ aws ec2 describe-images --filters "Name=name,Values=instance-20Aug15-i-*" 

Output :

IMAGES  x86_64  This is created by ami-backup.sh    xen ami-52020b00    008392659736/instance-20Aug15-i-127fb8df    machine instance-20Aug15-i-127fb8df 008392659736    False   /dev/sda1   ebs simple  available   hvm
BLOCKDEVICEMAPPINGS /dev/sda1
EBS True    snap-2b563aca   8   gp2

So please help me how parse this to get proper ami id or is there any other method to find ami id from ami name ?


Solution

  • awk is an inappropriate tool to parse JSON. jq would be substantially more appropriate if you like chaining tools.

    You can change the output format returned by aws-cli. That makes awk/grep more appropriate.

    You can also use --query instead of trying to parse it through awk. It uses the JMESPath syntax, which is slightly easier than the jq syntax.

    Here's some examples:

    $ aws ec2 describe-images --image-ids ami-6b1cd400 --query Images[].ImageId
    [
        "ami-6b1cd400"
    ]
    
    $ aws ec2 describe-images --image-ids ami-6b1cd400 --query Images[].ImageId --output text
    ami-6b1cd400