Adding tags to EBS volumes
March 22, 2018
Tagging all your Amazon resources is a must-have if you want to have an efficient billing follow-up. It’s effortless in most cases, but not always like with EBS volumes within an auto-scaling group. Even if it’s not natively possible, there is still a solution with AWS.
Currently, an auto-scaling group do not automatically apply its tags to EBS volumes attached to its EC2 instances. There is only a pending feature request, and no ETA is provided. Maybe it will be possible in the next months, perhaps not.
Until then, we have to implement something by ourselves.
After a discussion with the AWS support, we concluded that the best solution is to implement a custom logic at the EC2 instance boot through the launch configuration. The script is built on top of AWS CLI with the usage of EC2 instance metadata. Let’s have a look.
1#!/usr/bin/env bash
2set -euo pipefail
3
4# Retrieve the current EC2 instance ID.
5declare -r instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
6
7# Retrieve the AWS region ID where the EC2 instance is located.
8declare -r region_id=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone \
9 | grep -Po "(us|ca|ap|eu|sa)-(north|south)?(east|west|central)-[0-9]+")
10
11# Retrieve the volumes attached to the current EC2 instance.
12declare -r volumes=$(aws ec2 describe-instances \
13 --region "${region_id}" --instance-ids "${instance_id}" \
14 --query 'Reservations[*].Instances[*].BlockDeviceMappings[*].Ebs.VolumeId' --output text)
15
16# Retrieve the auto-scaling group name.
17declare -r asg=$(aws autoscaling describe-auto-scaling-instances \
18 --region "${region_id}" --instance-ids "${instance_id}" \
19 --query 'AutoScalingInstances[*].AutoScalingGroupName' --output text)
20
21# Retrieve the tags attached to the auto-scaling group.
22declare -r tags=$(aws autoscaling describe-tags \
23 --region "${region_id}" --filters Name=auto-scaling-group,Values="${asg}" \
24 --query 'Tags[*].{Key:Key,Value:Value}')
25
26# Add tags retrieved from the auto-scaling group to EBS volumes attached to the current EC2 instance.
27aws ec2 create-tags --region "${region_id}" --resources "${volumes}" --tags "${tags}"
The only requirement to implement that script is to attach the following policy on your EC2 instances. Otherwise, it won’t be possible for your EC2 instances to retrieve their tags and add them to EBS volumes.
1{
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Effect": "Allow",
6 "Action": [
7 "ec2:CreateTags",
8 "ec2:Describe*",
9 "autoscaling:Describe*"
10 ],
11 "Resource": "*"
12 }
13 ]
14}