DEV Community

loading...
Cover image for Easy EC2 Tagging

Easy EC2 Tagging

paulmicheli profile image Paul Micheli ・Updated on ・2 min read

Problem

I recently had the problem of inheriting an AWS account with over 1000+ EC2 resources that had an incorrect tagging strategy.

Resolve

After the manual effort of manually sorting through all the resources, and breaking them up into the correct groups. Instead of hours going through the console and tagging each resources with 4 tags I created the below script that will prompt for the required information and then tag them correctly.

I took roughly 15 minuets to run this script a few times and tag all of my resources.

I have a multi profile aws cli configuration, this will ask what profile to use and tag the resources there, if they don't exists it will error.

Update the profile line to match the profiles in your configuration file ~/.aws/config if you don't remove the below lines;

### If you don't use AWS Profiles in the CLI this can be removed
echo "Please choose AWS Account Profile"
select profile in profile1 profile2 profile3 profile4 
do
break
done

You can change the tag keys and expand on them if you need to add more.

You can input as many resource ID's on the single line as you like, use a space to separate them.

#!/bin/bash

echo "Use this script to tag EC2 Resources in the desired account"
echo "Multiple can be enter at once separated by a singe space."
echo "Below resources are supported using the ID"
echo "            Instance ID"
echo "            Snapshot ID"
echo "            Volumes ID" 
echo "            Security Group ID"
echo "            Elastic IPs Allocation ID"
echo " "
echo "----------------------------------------------------------- "

### If you don't use AWS Profiles in the CLI this can be removed
echo "Please choose AWS Account Profile"
select profile in profile1 profile2 profile3 profile4 
do

echo "Please list EC2 resources (Multiple can be entered at once)"
read resources
echo "Please Enter Cost Centre"
read cost
echo "Please Enter application"
read app
echo "Please Enter environment"
read environment
echo "Please Enter owner"
read owner

aws --profile=$profile ec2 create-tags --resources $resources  \
    --tags Key="Cost Centre",Value="$cost" \
      Key="application",Value="$app" \
      Key="environment",Value="$environment" \
      Key="owner",Value="$owner" 

echo "If no error's above tagging complete"
break
done

On to s3 tagging now.

Discussion

pic
Editor guide