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.