2

For example : I have 50 AWS instances. These instances's name of key in tags is AP1 , AP2 , AP3 , AP4 , AP5

Now I want to use the Python dictionary Grouping AWS instances by tag's name. Like this : {AP1:[1,2,3....10] , AP2:[11,12.....20] , AP3:[21,22,....30], AP4:[31.....40] , AP5:[41,42,.....50]}

According to this article : Obtaining tags from AWS instances with boto

I use this python script like this :

#!/usr/bin/env python
# -*- encoding: utf8 -*-

import boto.ec2
conn = boto.ec2.connect_to_region('us-west-1')
reservations = conn.get_all_instances()
InstanceMap={}
for reservation in reservations:
    for instance in reservation.instances:
        if 'Name' in instance.tags:
            InstanceMap[instance.tags['Name']].append(instance.id)

When I run this script, it show : [root@Redhat script]# python group.py

Traceback (most recent call last):

File "group.py", line 11, in

InstanceMap[instance.tags['Name']].append(instance.id)

KeyError: u'AP1'

What's wrong with my script ? Please provide me a correct python script.

Andrew
  • 602
  • 10
  • 23

1 Answers1

1

When you try to append to InstanceMap[instance.tags['Name']] you are trying to append to a list that the key (instance.tags['Name']) doesn't exists in InstanceMap yet, as it is empty.
First, you need to check if that key already exists in InstanceMap, and if it does, use append. Else, create it.

#!/usr/bin/env python
# -*- encoding: utf8 -*-

import boto.ec2
conn = boto.ec2.connect_to_region('us-west-1')
reservations = conn.get_all_instances()
InstanceMap={}
for reservation in reservations:
    for instance in reservation.instances:
        if 'Name' in instance.tags:
            tag_name = instance.tags['Name']
            if tag_name in InstanceMap
                InstanceMap[tag_name].append(instance.id)
            else:
                InstanceMap[tag_name] = [instance.id,]
DjLegolas
  • 76
  • 1
  • 4
  • , thanks very much for your reply. It solve my question. – Andrew Dec 30 '17 at 02:13
  • the question is when I print the dictionary to a file. There is letter 'u' header before the key and vaule of dictionary, how can I solve this question. – Andrew Dec 30 '17 at 02:40
  • please look at this question: https://stackoverflow.com/questions/48056933/if-i-just-wanted-to-get-ec2-instances-whose-value-of-tags-env-is-dev-how-sh – Andrew Jan 02 '18 at 07:15