Published on

How to Tag all your AWS IAM Users with Python


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.

import boto3

iam = 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 = ''

# generate tag list based on account type
def tag_template(username, environment):
    if '.' in username:
        account_type = 'human'
	email = username
        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}

    return template

# generate userlist
for response in paginator.paginate():

for iteration in range(len(unstructed_users)):
    for userobj in range(len(unstructed_users[iteration])):

# generate taggable userlist:
for user in userlist:
    tag_response = iam.list_user_tags(UserName=user)
    if len(tag_response['Tags']) == 0:

# tag users from taggable_list
for tag_user in taggable_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 lists
print('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:

Name: john.doe
Environment: test
Account_Type: human


Name: system-account
Environment: test
Account-Type: system

Thank You

Thanks for reading, feel free to check out my website, and subscrube to my newsletter or follow me at @ruanbekker on Twitter.

Buy Me A Coffee