dmn0972
dmn0972

Reputation: 373

list indices must be integers or slices, not str python3.6

I have a python script that pulls all of the EC2 instance ids and tags in all of the AWS accounts I own. I am trying to parse for only one value of one key. Specifically I only want to parse the Value of the Key email from the response, but I am getting the error: list indices must be integers or slices, not str. Below is my code and the json response.

Code:

import boto3
import json

conn = boto3.resource('ec2', 
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
aws_session_token=session_token)

instances = conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])

for instance in instances:
    host_list = instance.id
    host_tags = instance.tags
    print(host_tags['Key']['email']['Value'])

Sample JSON:

[{
    'Key': 'gitlab',
    'Value': 'true'
  }, {
    'Key': 'portfolio',
    'Value': 'xxx'
  }, {
    'Key': 'runner-manager-name',
    'Value': 'xxxxxx'
  }, ...
]

Error:

list indices must be integers or slices, not str

Upvotes: 2

Views: 2544

Answers (1)

John Hanley
John Hanley

Reputation: 81336

Your problem is with the lines:

host_tags = instance.tags
print(host_tags['Key']['email']['Value'])

Rewrite it like this:

host_tags = instance.tags
for tag in host_tags:
    print('Key: ' + tag['Key'] + ' Value: ' + tag['Value'])

instance.tags is an array of dict. You need to process each item (tag) in the array. Then you need to process the dict extracting its key / value pairs.

Upvotes: 4

Related Questions