Skip to content

Instantly share code, notes, and snippets.

@ajardin
Created August 21, 2020 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajardin/b085c7066a81212930355d5ce6f0d6b2 to your computer and use it in GitHub Desktop.
Save ajardin/b085c7066a81212930355d5ce6f0d6b2 to your computer and use it in GitHub Desktop.
Adding tags to EBS volumes
#!/usr/bin/env bash
set -euo pipefail
# Retrieve the current EC2 instance ID.
declare -r instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
# Retrieve the AWS region ID where the EC2 instance is located.
declare -r region_id=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | grep -Po "(us|ca|ap|eu|sa)-(north|south)?(east|west|central)-[0-9]+")
# Retrieve the volumes attached to the current EC2 instance.
declare -r volumes=$(aws ec2 describe-instances --region "${region_id}" --instance-ids "${instance_id}" --query 'Reservations[*].Instances[*].BlockDeviceMappings[*].Ebs.VolumeId' --output text)
# Retrieve the auto-scaling group name.
declare -r asg=$(aws autoscaling describe-auto-scaling-instances --region "${region_id}" --instance-ids "${instance_id}" --query 'AutoScalingInstances[*].AutoScalingGroupName' --output text)
# Retrieve the tags attached to the auto-scaling group.
declare -r tags=$(aws autoscaling describe-tags --region "${region_id}" --filters Name=auto-scaling-group,Values="${asg}" --query 'Tags[*].{Key:Key,Value:Value}')
# Add all tags retrieved from the auto-scaling group to all EBS volumes attached to the current EC2 instance.
aws ec2 create-tags --region "${region_id}" --resources "${volumes}" --tags "${tags}"
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:CreateTags",
"ec2:Describe*",
"autoscaling:Describe*"
],
"Resource": "*"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment