I was tasked to enforce mandatory tagging for ec2 instances, as there are a lot of machines and a lot of tags need to be attached to each machine, here I need a scripted way to get the job done.
How to achieve
Prepare a list of ec2 instances with default name tag only,
Open cloud shell or ssh to a linux box where AWSCli installed and configured to a AWS account, export the instances with ID to a csv file
Then add the header row for “instance ID” “tagA” ”valueA” ”tagB” ”valueB”
Create shell script to read the CSV file line by line, and add tags for each instance
Validate now ec2 instances with all tags attached
create cronjob to update tagging monthly
Conclusion
Now we have a scripted way to achieve adding different tags for multiple ec2 instances via AWS CLI and shell script, same method to any other AWS resources that needed to be tagged, together with cronjob, we can only update the csv file which regularly updates resource ID and tags we want to attach, upload the csv file, every month their tags will be updated accordingly.
Furthermore, the resouces can be queried by setting up filter by different tag criteria:
Or we can use lambda function together with AWS Config rules to list and remediate the untagged EC2 resource accordingly