AWS Classroom Series – 16/Apr/2020

How to query aws cli results

  • To query the results retreived from aws cli commands, aws supports jmespath

  • Pre-reqs:

    • Understanding JSON
  • To Query:

    • JMESPath: Helps in writing expressions to filter and search the json data
  • How to do that

  1. Write a query to get all the regions

    • Basic query and store output
    aws ec2 describe-regions > regions.json
    
    • lets get the first regions name
    aws ec2 describe-regions --query "Regions[0].RegionName"
    
    • lets get all the region names
    aws ec2 describe-regions --query "Regions[*].RegionName"
    
    • lets get the last region name
    aws ec2 describe-regions --query "Regions[-1].RegionName"
    
    • other fun stuff
    aws ec2 describe-regions --query "Regions[::2].RegionName"
    aws ec2 describe-regions --query "Regions[::-1].RegionName"
    
  2. Other jmes examples

    • Execute aws ec2 describe-instances > ec2info.json
    • Get image ids of all instances
    aws ec2 describe-instances --query "Reservations[*].Instances[0].ImageId"
    
    • Get Image id, Instance Id, Private Ip , Key Pair for all instances
    aws ec2 describe-instances --query "Reservations[*].Instances[0].{amiid: ImageId, instanceid: InstanceId, keypair: KeyName, PrivateIp: PrivateIpAddress}"
    
    • Write a query to describe all the images owned by amazon
    aws ec2 describe-images --owner amazon > images.json
    
    • Find count of number of images in region us-west-2 owned by amazon
    aws ec2 describe-images --owner amazon --query "length(Images[])"
    
    • Find count of number of images in region ap-south-1 owned by amazon
    aws ec2 describe-images --owner amazon --query "length(Images[])" --region ap-south-1
    
    • Write an aws cli query to find out images whose name starts with Windows and owner is microsoft
    aws ec2 describe-images --owner microsoft --query "Images[?starts_with(Name, 'Windows')]"
    
    • Show filtered information for above query
    aws ec2 describe-images --owner microsoft --query "Images[?starts_with(Name, 'Windows')].{amiid: ImageId, hypervisor: Hypervisor, virttype: VirtualizationType }"
    
    • Now try to write query to images whose name starts with aws
    aws ec2 describe-images --query "Images[?Name != `null`] |[?starts_with(Name, 'aws')].{amiid: ImageId, hypervisor: Hypervisor, virttype: VirtualizationType }"
    

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin