Why use TAGs
To help you manage your instances, images, and other Amazon EC2 resources, you can optionally assign your own metadata to each resource in the form of tags. This topic describes tags and shows you how to create them.
(Ref: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html)
Problem :
Sometimes tags are applied in environments prior to developing a tagging strategy. The problem in exponentially increased with the size of the environment and the number of users creating resources.
Currently we are looking for a solution to remove specific unwanted tags from EC2 instances or modify the tag values which are incorrect.
For this purpose , the below mentioned script was developed that solves the problem for AWS.
Solution :
The below mentioned script performs the following tasks
- Get the list of all the EC2 instances in the tenant
- Loop through all the EC2 instances
- Get values of all the tags in the environment
- Check each Tag Key and Tag Value.
- Modify of remove the tag value ( based on requirement )
Code:
#Set up the AWS profile using the Access Key and Secret Key Set-AWSCredential -AccessKey AccessKey -SecretKey SecretKEy -StoreAs ProfileName #Getting the list of all the instances in the Tenant $instances = (Get-EC2Instance -ProfileName ProfileName -Region RegionName).Instances $tagkeytoremove = 'TAG1' # Declaring the TAG Key to remove / modify $tagvaluetoremove = 'ChangePLease' # Declaring the Tag Value to Remove / Modify $NewTagValue = "NewTagValue" # Declaring the new tag value. Foreach ( $instance in $instances ) # Looping through all the instances { $OldTagList = $instance.tags foreach ($tag in $OldTagList) # Looping through all the Tags { if($tag.key -ceq $tagkeytoremove -and $tag.Value -ceq $tagvaluetoremove ) # Comparing the TAG Key and Values { Remove-EC2Tag -Resource $instances.instanceid -Tag $tag -Force # Removing the Old Tag Key Value Pair New-EC2Tag -Resource $instances.instanceid -Tag @{ Key=$tag.key;Value=$NewTagValue} -Force #Adding the New Tag Key Value pair. } } } # Loop Ends
Hi Syed,
Thanks for this blog post. I am trying to achieve the same thing but with AWS CLI
#Getting the list of all the instances in the Tenant
$instances = (Get-EC2Instance -ProfileName ProfileName -Region RegionName).Instances
Foreach ( $instance in $instances ) # Looping through all the instances
$OldTagList = $instance.tags
AWS CLI
instance=$(aws ec2 describe-instances –query ‘Reservations[*].Instances[*] –output json)
for i in “${instance[@]}” # Looping through all the instances
do
$OldTagList = $instance.tags///Not able to find the exact operation for AWS CLI???
Not able to proceed further to check the Tag Key and Value