Managing AWS IAM Users with Python and boto3
In this tutorial, we are going to manage IAM Users with Python and its boto3 library. Boto 3 is a standard library to access AWS services using Python. As we have learned in the last tutorial, using AWS IAM (Identity Access Management) we can create users, manage their permissions, create groups and delete users. Let us see how we can do these using Python
Create IAM Users with Python and boto3
When we create the AWS account we are signed in as root user. It is recommended to create a new user and use that to access AWS resources. Also, we need to create different users for everyone who wants to access AWS in different capacities.
Creating a new user in python is very easy. You can create a client or resource object for IAM and use its create user function. Additionally, you can pass tags to identify that user.
1 2 3 4 5 6 7 8 9 10 |
import boto3 iam = boto3.resource('iam') #using resource representing IAM created_user = iam.create_user( UserName='first_user' ) print(created_user) #running file python3 create_user.py # expected output iam.User(name='first_user') |
1 2 3 4 5 6 7 8 9 10 11 12 |
import boto3 iam = boto3.client('iam') #using low lavel clinet to access IAM created_user = iam.create_user( UserName='second_user', Tags=[ # adding tags to identify that user in IAM { 'Key': 'Env', 'Value': 'Test' } ] ) print(created_user) |
1 2 3 4 5 6 |
#running program python3 create_user.py #output, using IAM clinet will give you more data about created user {'User': {'Path': '/', 'UserName': 'second_user', 'UserId': 'AIDAS3CARBCB4ISBODLJE', 'Arn': 'arn:aws:iam::195556345987:user/second_user', 'CreateDate': datetime.datetime(2019, 8, 18, 6, 14, 41, tzinfo=tzutc()), 'Tags': [{'Key': 'Env', 'Value': 'Test'}]}, 'ResponseMetadata': {'RequestId': '7714580d-c17f-11e9-9a35-37dd9682876d', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requ estid': '7714580d-c17f-11e9-9a35-37dd9682876d', 'content-type': 'text/xml', 'content-length': '600', 'date': 'Sun, 18 Aug 2019 06:14:40 GMT'}, 'RetryAttempts': 0}} |
Attach a Policy to a User
When you create a new user, by default he/she will have no permissions. This is in accordance with AWS best practice to grant the least required privileges to a user. So we will have to attache each user required level of permissions. And we can do that by using IAM policies. Each IAM policy is identified by AWS ARN (Amazon Resource Name). We need to get that ARN before we can attach it to the user. We can get that ARN from the AWS console. If you want to learn more about IAM policies and how to manage them, you can read another article I have written.
In the above image, we have copied ARN of S3 read access. The next step is to assign that to our user.
1 2 3 4 5 6 7 8 |
import boto3 iam = boto3.client('iam') # IAM low level client object response = iam.attach_user_policy( UserName = 'first_user', #Name of user PolicyArn = 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess' # Policy ARN which you want to asign to user ) print(response) |
You can validate the result in the AWS console. We can see that the user now has s3 read access permissions.
Add User to Group
Adding permissions to each individual user is cumbersome especially when you have hundreds of users. So it is always a best practice to create Groups and manage permissions at a group level. We can create groups like HR, Admin, Testers, Developers and more. Users in one group will have all permissions attached to that group.
Before we add a user to a group, we need to make sure that the group is present in AWS IAM. We can create a group first and then add a user to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import boto3 iam = boto3.client('iam') # IAM low level client object """ We need to make sure group is present in AWS IAM As we do not have group named Tester, We will create it first IN your case you can skip this step if group is already created in your account """ create_group_response = iam.create_group(GroupName = 'Tester') #adding user to Tester group response = iam.add_user_to_group( UserName = 'first_user', #Name of user GroupName = 'Tester' ) print(response) |
You can also use simpler methods provided by the IAM resource object to add a user to a group.
1 2 3 4 5 |
iam_resource = boto3.resource('iam') #resource representing IAM group = iam_resource.Group('Tester') # Name of group response = group.add_user( UserName='second_user' #name of user ) |
List All Users
Let us write code to list all users in our account. We get a response object with all details like user name, permissions, created date, etc. We can format and print the required details below.
1 2 3 4 5 6 7 8 9 10 11 |
import boto3 iam = boto3.client('iam') users = iam.list_users() for user in users['Users']: print("UserName: {0}\nCreateDate: {1}\n" .format(user['UserName'], user['CreateDate'])) # sample output UserName: first_user CreateDate: 2019-08-18 06:11:15+00:00 UserName: second_user CreateDate: 2019-08-18 06:14:41+00:00 |
If you have hundreds of users, then you might want to use the paginator method. It returns iterator for all users in your account.
1 2 3 4 5 6 7 |
import boto3 iam = boto3.client('iam') pages = iam.get_paginator('list_users') for page in pages.paginate(): for user in page['Users']: print("UserName: {0}\nCreateDate: {1}\n" .format(user['UserName'], user['CreateDate'])) |
Get Specific User Details
Now let us get details for a specific user. It is again a very simple script using Python.
1 2 3 4 5 |
import boto3 iam = boto3.client('iam') #Name of user whoes details we need response = iam.get_user(UserName = 'second_user') print(response) |
If we pass no argument to get_user method, it will run details of user which boto3 is using to access AWS services. If you want to learn more about AWS CLI configure and how boto3 uses those user profiles you can read this article.
1 2 3 4 |
import boto3 iam = boto3.client('iam') response = iam.get_user() print(response) |
Delete User
More often than not, we need to delete users from our AWS account. We can do that simply running delete user function. But before deleting the user from IAM, we need to remove that user from all groups which he/she is part of. Also, we need to remove all policies which are directly assigned to that user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import boto3 iam = boto3.client('iam') """ Before deleting user we need to remove it from Group Otherwise we will get following error An error occurred (DeleteConflict) when calling the DeleteUser operation: Cannot delete entity, must remove users from group first. """ response = iam.remove_user_from_group( GroupName='Tester', UserName='second_user' ) print(response) response = iam.delete_user( UserName='second_user' ) print(response) |
We can also use the resource class to delete the user. In this case, we first need to remove polices attached to that user before deleting it along with removing a user from Groups.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
iam = boto3.resource('iam') """ Before deleting user we need to remove policies attached to that user Otherwise we will get following error An error occurred (DeleteConflict) when calling the DeleteUser operation: Cannot delete entity, must detach all policies first. """ #policy arn which we want to detach from user policy = iam.Policy('arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess') response = policy.detach_user( UserName='first_user' ) group = iam.Group('Tester') response = group.remove_user( UserName='first_user' ) #Now we can delete user user = iam.User('first_user') user.delete() |
Conclusion
We have learned how to manage IAM users using Python and boto3. and you must have seen that it’s very easy. I hope it helped you. You can get all of this code in my Github repo.
If you want to learn how to perform these operations using AWS CLI please read this article. See you again.