Ruan Bekker's Blog

From a Curious mind to Posts on Github

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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 = '@example.com'

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

for iteration in range(len(unstructed_users)):
    for userobj in range(len(unstructed_users[iteration])):
        userlist.append((unstructed_users[iteration][userobj]['UserName']))

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

# 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:

1
2
3
4
5
6
7
8
9
10
11
Name: john.doe
Email: john.doe@example.com
Environment: test
Account_Type: human

or:

Name: system-account
Email: system-admin@example.com
Environment: test
Account-Type: system

Thank You

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.