Pages

Subscribe:

Sunday, August 26, 2018

Tagging EBS Volumes with Same tags as on EC2 instances in Autoscaling

Propagate the tags from a instance in an autoscaling group to the EBS volumes attached.

Although autoscaling group allows to apply tags to the instances this doesn't propagate to the instance volumes. So some scripting on user data section is needed during instance launch to properly tag the volumes of instances created by the autoscaling group.

You can use the below script to apply the tags to the EBS Volumes in an autoscaling group which should be created in the userdata field in the launch configuration of the autoscaling group. Also you need to attach a IAM role to the instance with the permissions of describe-instances,create-tags etc.



#!/bin/bash
#
id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
region=$(curl -s "http://169.254.169.254/latest/meta-data/placement/availability-zone" | sed 's/[a-z]$//')

# Get volumes
vol_list=$(aws ec2 describe-instances --instance-ids $id --region=$region --query 'Reservations[*].Instances[*].BlockDeviceMappings[*].Ebs.VolumeId' --output text)

# Get Tags, formatted as JSON, strip aws: tags as they are reserved
tag_list=$(aws ec2 describe-instances --instance-id $id --region $region --query 'Reservations[].Instances[].Tags[?!starts_with(Key, `aws:`) ] | []')

# Tag the volume(s) on the instance
aws ec2 create-tags --resources $vol_list --tags "$tag_list" --region=$region

0 comments:

Post a Comment