Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boto EC2: Create an instance with tags

Tags:

Is there a way with the boto python API to specify tags when creating an instance? I'm trying to avoid having to create an instance, fetch it and then add tags. It would be much easier to have the instance either pre-configured to have certain tags or to specify tags when I execute the following command:

ec2server.create_instance(         ec2_conn, ami_name, security_group, instance_type_name, key_pair_name, user_data     ) 
like image 494
stevebot Avatar asked Nov 09 '11 19:11

stevebot


People also ask

How do I add tags to multiple EC2 instances?

To add tags to—or edit or delete tags of—multiple resources at once, use Tag Editor. With Tag Editor, you search for the resources that you want to tag, and then manage tags for the resources in your search results. Sign in to the AWS Management Console. On the navigation bar, choose Services.


1 Answers

This answer was accurate at the time it was written but is now out of date. The AWS API's and Libraries (such as boto3) can now take a "TagSpecification" parameter that allows you to specify tags when running the "create_instances" call.


Tags cannot be made until the instance has been created. Even though the function is called create_instance, what it's really doing is reserving and instance. Then that instance may or may not be launched. (Usually it is, but sometimes...)

So, you cannot add a tag until it's been launched. And there's no way to tell if it's been launched without polling for it. Like so:

reservation = conn.run_instances( ... )  # NOTE: this isn't ideal, and assumes you're reserving one instance. Use a for loop, ideally. instance = reservation.instances[0]  # Check up on its status every so often status = instance.update() while status == 'pending':     time.sleep(10)     status = instance.update()  if status == 'running':     instance.add_tag("Name","{{INSERT NAME}}") else:     print('Instance status: ' + status)     return None  # Now that the status is running, it's not yet launched. The only way to tell if it's fully up is to try to SSH in. if status == "running":     retry = True     while retry:         try:             # SSH into the box here. I personally use fabric             retry = False         except:             time.sleep(10)  # If we've reached this point, the instance is up and running, and we can SSH and do as we will with it. Or, there never was an instance to begin with. 
like image 129
Craig Ferguson Avatar answered Jan 02 '23 22:01

Craig Ferguson