Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (12.9k points)

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

    )

1 Answer

0 votes
by (18.2k points)

You cannot add a tag on an instance untill it has been completely launced. So, is you want to create a script to add tags to instances, you will also have to make sure that the instance is launched as well as up and running before you can add a tag. So, your script should look something like:

reservation = conn.run_instances( ... )

instance = reservation.instances[0]

# Check up on its status, if it's running then add a tag.

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

# Check if the instance is completely up and running. The only way to tell if it's fully up is to try to SSH in.

if status == "running":

    retry = True

    while retry:

        try:

            retry = False

        except:

            time.sleep(10)

# If we've reached this point, the instance is up and running, so we can SSH into it and do as we will with it. 

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...