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
)
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.