Skip to content

Instantly share code, notes, and snippets.

@gurchik
Created August 19, 2024 15:26
Show Gist options
  • Save gurchik/86413d785218bbdd7c5325a707e1374c to your computer and use it in GitHub Desktop.
Save gurchik/86413d785218bbdd7c5325a707e1374c to your computer and use it in GitHub Desktop.
Update EC2 tags for instances in an Auto Scaling Group

update-tags.py

Update EC2 tags for instances in an Auto Scaling Group.

When changing the tags for an Auto Scaling Group, these changes only apply to new instances launched. Therefore, you need something to apply the new tags to existing instances.

import boto3
ASG_NAME = "replace-me"
TAGS = [
{
"Key": "foo",
"Value": "bar",
},
]
def get_instances(asg_name):
client = boto3.client('autoscaling')
response = client.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name])
assert len(response["AutoScalingGroups"]) == 1
asg = response["AutoScalingGroups"][0]
instances = asg["Instances"]
return list(i["InstanceId"] for i in instances)
def update_tags(instance_ids, tags):
client = boto3.client('ec2')
client.create_tags(
Resources=instance_ids,
Tags=tags,
)
if __name__ == "__main__":
instances = get_instances(ASG_NAME)
update_tags(instances, TAGS)
print(f"{len(instances)} instances updated")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment