How to add a tag to an autoscale spun EC2 instance using boto?

Does anyone know how to tag an AWS Autoscale spun EC2 instance via boto? I would like all Autoscale EC2 instances to have a prefix of 'as-'.

Thanks


Solution 1:

I figured this out.

You assign a 'Name' tag to an AWS Autoscale group after it is created. The trick is to set the 'propagate_at_launch' flag to True when passing it to the Autoscale Tag object. This flag when set to True ensures that the tag will be applied to any Autoscale spun EC2 instance after the tag is created. An example follows:

import boto
from boto.ec2.autoscale import Tag

# Make sure your access keys are stored in ~/.boto
conn = boto.connect_autoscale()

# This assumes you have already setup an elastic load balancer
# and a launch configuration
ag = AutoScalingGroup(group_name=group_name,
                      load_balancers=[load_balancer],
                      availability_zones=availability_zones,
                      launch_config=config,
                      min_size=min_size,
                      max_size=max_size)

# Create auto scaling group
conn.create_auto_scaling_group(ag)

# Fetch the autoscale group after it is created
auto_scaling_group = conn.get_all_groups(names=[group_name])[0]

# Create a Tag for the austoscale group
as_tag = Tag(key='Name',
             value = 'as-instance',
             propagate_at_launch=True,
             resource_id=group_name)

# Add the tag to the autoscale group
conn.create_or_update_tags([as_tag])

Voila! Now whenever an EC2 instance is spun from this Autoscale group based on CloudWatch Alarms i.e. scale up based on CPU utilization thresholds or some other metric...that instance will have a name value = 'as-instance'

Cheers