Reputation: 1731
ec2 is tagged with the follwoing:
env,project,purpose
have a list of instances that belong to a project and to a environment.
conn = ec2.connect_to_region(region,aws_access_key_id=access_key,aws_secret_access_key=secret_key)
reservations = conn.get_all_instances(filters={"tag:env":env, "tag:project":project})
instances = [i for r in reservations for i in r.instances]
instances_id = [i.id for i in instances]
Now need a way to get the value of the tag 'purpose' for each instance in the list instance_id.
So that i can take actions based on the purpose.
I am going through the get_all_tags function of boto, but am unable to figure out how to get each instance_id in the filters of the function. And one more thing i only need the unique values for purpose.
How do i go about getting this done?
Upvotes: 2
Views: 400
Reputation: 5118
I believe you need a way to group all instances based on the value of the purpose tag.
def get_instances_by_purpose(access_key,secret_key,region,env,project):
conn = ec2.connect_to_region(region,aws_access_key_id=access_key,aws_secret_access_key=secret_key)
reservations = conn.get_all_instances(filters={"tag:env":env, "tag:project":project})
instances = [i for r in reservations for i in r.instances]
instances_by_purpose = {}
[instances_by_purpose.setdefault(i.tags.get('purpose'), []).append(i.id) for i in instances]
return instances_by_purpose
The instances_by_purpose
variable contains a dictionary with keys that are all possible values of purpose encountered, and the value for each purpose is a list of all instances that have that purpose.
e.g. purpose values = "webserver", "backupserver", "logging" output will be {"webserver":["i-sdfsfd","i-sdfsfd","i-sdfsfd"], "backupserver":["i-werwer","i-erwer","i-3242erds"], ..... }
You can change this so it is a list of public IPs, or private IPs, or any other attribute you can pull from the instance object. e.g. if you want public IPs, change the list comprehension as follows:
[instances_by_purpose.setdefault(i.tags.get('purpose'), []).append(i.ip_address) for i in instances]
You can then feed this into another function that processes this payload based on purpose.
Upvotes: 1
Reputation: 2759
try this:
for inst in instances:
if 'purpose' in inst.tags:
print "%s -> %s" % (inst.id, inst.tags['purpose'])
output:
i-0123abcd -> foo
i-0123abcf -> bar
Upvotes: 0