Wednesday, October 27, 2021

[SOLVED] Problem parsing json from "aws ec2 describe-instances" output

Issue

I'm trying to parse the following json that was output from the aws ec2 describe-instances cli command:

    "Reservations": [
        {
            "Instances": [
                {
                    "Monitoring": {
                        "State": "disabled"
                    },
                    "PublicDnsName": "ec2xxxxxxxxxx.us-west-2.compute.amazonaws.com",
                    "StateReason": {
                        "Message": "Client.UserInitiatedShutdown: User initiated shutdown",
                        "Code": "Client.UserInitiatedShutdown"
                    },
                    "State": {
                        "Code": 80,
                        "Name": "stopped"
                    },
                    "EbsOptimized": false,
                    "LaunchTime": "2016-11-28T20:17:05.000Z",
                    "PublicIpAddress": "x.x.110.2",
                    "PrivateIpAddress": "x.x.2.2",

I'm able to parse "LaunchTime" just fine, but using the same code, I cannot parse "PublicIpAddress" or "PrivateIpAddress. Logically it doesn't make any sense.

This is my code:

#!/usr/bin/python3

import json

with open('all-instances.json') as f:
    data = json.load(f)

for myInstance in data['Reservations']:
    print(myInstance['Instances'][0]['LaunchTime']) #This works
    print(myInstance['Instances'][0]['PublicIpAddress']) #This doesn't work

This is the output I get:

Traceback (most recent call last):
  File "./json-parsing.py", line 15, in <module>
    print(myInstance['Instances'][0]['PublicIpAddress'])
KeyError: 'PublicIpAddress'

So my question is; why am I able to get the value for LaunchTime but not PublicIpAddress even though they're in the same python dictionary and I'm using the same exact code? Thanks for any assistance. Eric

EDIT:

This will account for instances that don't have a public IP and will continue without throwing an error.

if 'PublicIpAddress' in myInstance['Instances'][0]:
        print(myInstance['Instances'][0]['PublicIpAddress'])
else:
   print("None")

Solution

I think it's because, one of the instances, does not have PublicIpAddress. thats the only possibility for this to happen



Answered By - Arun K