DEV Community

Cover image for EC2 Tagging MKII
Paul Micheli
Paul Micheli

Posted on • Updated on

EC2 Tagging MKII

A few weeks ago I posted about a crude bash script to tag your EC2 resources, I have since tweaked the script to use the instance ID to find the volumes and snapshots associated with each instance ID.

It will also dynamically pull in account to use from your AWS config file.

Have Fun

#!/bin/bash

## Functions

tag_rescources () {
aws --profile=$profile --region=$region ec2 create-tags --resources $1 \
    --tags Key="COST CENTRE",Value="$cost" \
      Key="APP",Value="$app" \
      Key="ENVIRONMENT",Value="$environment" \
      Key="OWNER",Value="$owner" 
}

get_volumes (){
aws --profile=$profile --region=$region ec2 describe-volumes \
  --filters Name=attachment.instance-id,Values=$1 \
  --query "Volumes[].VolumeId" --output=text
}

get_snapshots(){
aws --profile=$profile --region=$region ec2 describe-snapshots \
  --filters Name=volume-id,Values=$1 \
  --query "Snapshots[].SnapshotId" --output=text
}


## Script
echo "Use this script to tag EC2 instance in the desired account"
echo "Multiple can be enter at once seperated by a singe space."
echo "Below resources are supported using the ID"
echo "            Instance ID"
echo "            Security Group ID"
echo "            Elastic IPs Allocation ID"
echo " "
echo "----------------------------------------------------------- "
echo "Please choose AWS Account Profile"
select profile in `grep '^\[' ~/.aws/config|sed -r 's/\[|\]//g'|awk '{print $2}'`
do
   echo "Please choose AWS Region"
   select region in eu-west-1 eu-central-1 us-east-1
   do

   echo "Please list EC2 Instance ID"
   echo "Multiple can be entered at once, seperated by a singe space."
   read instance
   echo "Please Enter COST CENTRE"
   read cost
   echo "Please Enter APP"
   read app
   echo "Please Enter ENVIRONMENT"
   read environment
   echo "Please Enter OWNER"
   read owner

   ## Tagging EC2 Instances
   for i in $instance
   do
      tag_rescources $i
      echo "Tagging EC2 Instances $i"
   done

   ## Tagging Volunmes
   #! a nested loop is used as the get volume function can only filter one volume at a time
   for i in $instance
   do
         for j in `get_volumes $i`
         do
            echo "Tagging Volume $j beloning to Instance $i"
            tag_rescources $j
         done
   done

   ## Tagging Snapshots
   #! a nested loop is used as the get snapshot function can only filter one volume at a time
   volumes=`get_volumes $instance`
   for i in $volumes
   do
         for j in `get_snapshots $i`
         do
            echo "Tagging SnapShot $j belonging to Volume $i"
            tag_rescources $j
         done
   done

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

Top comments (0)