Ziva
Ziva

Reputation: 3521

Boto3 - tag instance during creating

I'm currently working with the AWS EC2 instances. I want to start several instances, which are responsible for different tasks. To create and start instances I'm using the below function:

def ec2start(num):
    ec2.create_instances( 
        ImageId='image_id', 
        InstanceType='instance_type',
        SecurityGroupIds= [ 'security_group_id' ],
        MinCount=int(num), 
        MaxCount=int(num)
        )

However, since I have several running instances, but some of them perform similar operations, I'm using @roles to call one function on several instances and speed up everything. To be able to use a particular function on selected instances I'm adding to every instance a tag. So far, to tag an instance I'm using a following function:

def ec2tagInstance(ids, tagname):
    ec2.create_tags(Resources=[ids], Tags=mytags)
    instances = ec2.instances.filter(InstanceIds=[ids])
    for instance in instances:
        for tag in instance.tags:
            if tag["Key"] == "Type":
                tag["Value"] = tagname

However, right now I have to first create (start) an instance and then, I have to call a function ec2tagInstance with a specific id, to be able to tag it. Is it possible to add a tag to an instance at the same moment when I'm creating (starting) a new instance?

Upvotes: 0

Views: 524

Answers (1)

garnaat
garnaat

Reputation: 45916

There really isn't a way to assign tags to an instance when you create it. The EC2 RunInstances API request does not accept a Tags parameter.

You could write your own function that creates the instances and tags them immediately after but there is no way to do it with a single API call.

Upvotes: 3

Related Questions