Let’s say that all your IAM users are named in name.surname and your system accounts are named as my-system-account and you find yourself in a position that you need to tag all your IAM users based on Human/System account type.
With AWS and Python’s Boto library, it makes things easy. We would list all our users, loop through each one and tag them with the predefined tag values that we chose.
Batch Tagging AWS IAM Users with Python
This script wil tag all users with the tag: Name, Email, Environment and Account_Type.
importboto3iam=boto3.Session(profile_name='test',region_name='eu-west-1').client('iam')paginator=iam.get_paginator('list_users')iam_environment='test'unstructed_users=[]userlist=[]taggable_users=[]already_tagged_users=[]email_address_domain='@example.com'# generate tag list based on account typedeftag_template(username,environment):if'.'inusername:account_type='human'email=usernameelse:account_type='system'email='system-admin'template=[{'Key':'Name','Value':username.lower()},{'Key':'Email','Value':email.lower()+email_address_domain},{'Key':'Environment','Value':environment},{'Key':'Account_Type','Value':account_type}]returntemplate# generate userlistforresponseinpaginator.paginate():unstructed_users.append(response['Users'])foriterationinrange(len(unstructed_users)):foruserobjinrange(len(unstructed_users[iteration])):userlist.append((unstructed_users[iteration][userobj]['UserName']))# generate taggable userlist:foruserinuserlist:tag_response=iam.list_user_tags(UserName=user)iflen(tag_response['Tags'])==0:taggable_users.append(user)else:already_tagged_users.append(user)# tag users from taggable_listfortag_userintaggable_users:user_template=tag_template(tag_user,iam_environment)print(tag_user,user_template)response=iam.tag_user(UserName=tag_user,Tags=user_template)# print listsprint('Userlists: {}'.format(userlist))print('Taggable Users: {}'.format(taggable_users))print('Already Tagged Users: {}'.format(already_tagged_users))
After it completes, your IAM users should be tagged in the following format:
Please feel free to show support by, sharing this post, making a donation, subscribing or reach out to me if you want me to demo and write up on any specific tech topic.