Search code examples
pythonpython-3.xpython-2.7boto3amazon-emr

Need help in fetching a particular value from the json output


I need to obtain the Tag values from the below code, it initially fetches the Id and then passes this to the describe_cluster, the value is then in the json format. Tryging to fetch a particular value from this "Cluster" json using "GET". However, it returns a error message as "'str' object has no attribute 'get'", Please suggest.

Here is a reference link of boto3 which I'm referring: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/emr.html#EMR.Client.describe_cluster

import boto3
import json
from datetime import timedelta

REGION = 'us-east-1'

emrclient = boto3.client('emr', region_name=REGION)
snsclient = boto3.client('sns', region_name=REGION)

def lambda_handler(event, context):
    EMRS = emrclient.list_clusters(
    ClusterStates = ['STARTING', 'RUNNING', 'WAITING']
    )

    clusters = EMRS["Clusters"]
    for cluster_details in clusters :
        id = cluster_details.get("Id")

        describe_cluster = emrclient.describe_cluster(
            ClusterId = id
            )

        cluster_values = describe_cluster["Cluster"]

        for details in cluster_values :
            tag_values = details.get("Tags")
            print(tag_values)

Solution

  • The error is in the last part of the code.

    describe_cluster = emrclient.describe_cluster(
        ClusterId = id
        )
    
    cluster_values = describe_cluster["Cluster"]
    
    for details in cluster_values: # ERROR HERE
        tag_values = details.get("Tags")
        print(tag_values)
    

    The returned value from describe_cluster is a dictionary. The Cluster is also a dictionary. So you don't need to iterate over it. You can directly access cluster_values.get("Tags")