Skip to content

Instantly share code, notes, and snippets.

@wehappyfew
Last active August 29, 2015 14:17
Show Gist options
  • Save wehappyfew/66a18d86e8e98bfc88b4 to your computer and use it in GitHub Desktop.
Save wehappyfew/66a18d86e8e98bfc88b4 to your computer and use it in GitHub Desktop.
A function that tags all the newly created instances based on their 'pending' state.Of course it can be used for tagging any other state just by providing different argument.
def tag_instances(connection,tag , instance_state="pending"):
"""
-The function must be run immediately after the spawn of an instance!!!-
1. The function fetches all the instances
2. Filters them by instance-state-name:pending
(for a short period the newly created instances are 'pending' before becoming 'running')
3. Tags them with the user defined tag.
4. Returns the just tagged instances (ids) for future reference
"""
newly_tagged_instances = []
reserves = connection.get_all_instances(filters={"instance-state-name":instance_state})
for r in reserves:
for instance in r.instances:
print "--Creating instance-- \n", "ID: "+str(instance.id)+"\n", "Status: "+instance.state
# set a tag
instance.add_tag("Name", tag ) ; print "Name: "+tag+"\n"
# save the newly created instance to the list
newly_tagged_instances.append( instance.id )
return newly_tagged_instances
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment