Manage IAM Groups using Python and AWS CLI

Updated On April 12, 2020 | By Mahesh Mogal

In this article, we are going to manage AWS IAM Groups using Python and AWS CLI. IAM Groups are the recommended way to manage AWS permissions for a collection of users. Let us learn how we can master IAM group operations.

Create IAM Group

We can create the IAM group in the following ways in python and AWS CLI.

import boto3

#creating group with client
iam = boto3.client('iam') # IAM low level client object
create_group_response = iam.create_group(GroupName = 'group1')
print(create_group_response)

#createing group with resource
iam = boto3.resource('iam') #resource representing IAM
response = iam.create_group(
    GroupName='group2'
)
print(response)
#using AWS CLI
# command for creating IAM Group
mahesh@mahesh:~$ aws iam create-group \
> --group-name 'group2'
{
    "Group": {
        "Path": "/",
        "GroupName": "group2",
        "GroupId": "AGPAS3CARBCB7H4NRBUHW",
        "Arn": "arn:aws:iam::195556345987:group/group2",
        "CreateDate": "2019-08-18T09:34:55Z"
    }
}

List All Groups in IAM

We can list all IAM groups in AWS.

import boto3

#listing all groups using client
iam = boto3.client('iam') # IAM low level client object
response = iam.list_groups()

for group in response['Groups']:
    print("GroupName: {0}\nCreateDate: {1}\n"
    .format(group['GroupName'], group['CreateDate']))

We can achieve the same using AWS CLI using the following command

mahesh@mahesh:~$ aws iam list-groups

Adding Users to IAM Group

We can add users to the group with Python using the following script.

import boto3

iam = boto3.client('iam') # IAM low level client object

#adding user to group
response = iam.add_user_to_group(
UserName = 'user1_g1', #Name of user
GroupName = 'group1'
)

print(response)

iam_resource = boto3.resource('iam') #resource representing IAM
group = iam_resource.Group('group1') # Name of group

response = group.add_user(
UserName='user2_g1' #name of user
)

print(response)

Using AWS CLI, we can run the following command to add a user to the group.

# adding user to IAM Group
mahesh@mahesh:~$ aws iam add-user-to-group \
> --group-name 'group2' \
> --user-name 'user3_g2'

Listing All users in specific IAM group

Often, we might need to list all users who belong to a particular group. Using Python, we can list users using the following script.

import boto3

#get specific group using client
iam = boto3.client('iam') # IAM low level client object
response = iam.get_group(
GroupName='group1'
)

print(response['Group']['GroupName'])

#list all users in that group
for user in response['Users']:
    print("UserName: {0}\nCreateDate: {1}\n"
    .format(user['UserName'], user['CreateDate']))

For doing the same in AWS CLI, we need to run the following command.

mahesh@mahesh:~$ aws iam get-group \
> --group-name 'group2'
{
    "Users": [
        {
            "Path": "/",
            "UserName": "user4_g2",
            "UserId": "AIDAS3CARBCB2C4EDOCVJ",
            "Arn": "arn:aws:iam::195556345987:user/user4_g2",
            "CreateDate": "2019-08-18T14:03:03Z"
        },
        {
            "Path": "/",
            "UserName": "user3_g2",
            "UserId": "AIDAS3CARBCBRW2GMRXRE",
            "Arn": "arn:aws:iam::195556345987:user/user3_g2",
            "CreateDate": "2019-08-18T14:03:03Z"
        }
    ],
    "Group": {
        "Path": "/",
        "GroupName": "group2",
        "GroupId": "AGPAS3CARBCBVVJM7KFWW",
        "Arn": "arn:aws:iam::195556345987:group/group2",
        "CreateDate": "2019-08-18T13:42:24Z"
    }
}

Removing Users from IAM groups

We can remove users from the IAM group using python using the function below.

import boto3

iam = boto3.client('iam')

response = iam.remove_user_from_group(
    GroupName='group2',
    UserName='user3_g2'
)
#removing user from group using AWS CLI
mahesh@mahesh:~$ aws iam remove-user-from-group \
> --user-name 'user3_g2' \
> --group-name 'group2'

Attaching Policies to IAM Group

We can manage permissions for all users in the group with IAM policies. We can attache policy to IAM group and it will affect all users in that group. Let us write a script to attach a policy to the IAM group using Python.

import boto3

#attaching policy using client
iam = boto3.client('iam') # IAM low level client object
#attaching admin access level policy to group
response = iam.attach_group_policy(
    GroupName='group1',
    PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
)
print(response)


#attaching policy using resource
iam = boto3.resource('iam')
group = iam.Group('group2')
#attaching s3 admin access policy to group
response = group.attach_policy(
    PolicyArn='arn:aws:iam::aws:policy/AmazonS3FullAccess'
)
print(response)

Listing Attached policies to IAM Group

It is easier to manage policies for users at the group level. Any policy attached to that group will be applied to all of its members. We can check all policies attached to that group using the below method

import boto3

#listing all policies attached to group using client
iam = boto3.client('iam') # IAM low level client object
response = iam.list_attached_group_policies(
    GroupName='group1'
    )


for policy in response['AttachedPolicies']:
    print('PolcyName: {0}\nPolicyARN: {1}\n'.format(
    policy['PolicyName'], policy['PolicyArn']
    ))

#listing all policies attached to group using resource
iam = boto3.resource('iam') #resource representing an AWS IAM
group = iam.Group('group2')

policy_iterator = group.attached_policies.all()

for policy in policy_iterator:
    print(policy)

We can do the same thing using AWS CLI as well.

mahesh@mahesh:~$ aws iam list-attached-group-policies \
> --group-name 'admin'
{
    "AttachedPolicies": [
        {
            "PolicyName": "AdministratorAccess",
            "PolicyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
        }
    ]
}

Removing attached policies to IAM group

We can remove the attached policies to IAM groups.

import boto3

#detach policy from group using client
iam = boto3.client('iam') # IAM low level client object
response = iam.detach_group_policy(
    GroupName='group1',
    PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
)
print(response)

#detach policy from group using resource
iam = boto3.resource('iam') #resource representing an AWS IAM
group = iam.Group('group2')

response = group.detach_policy(
    PolicyArn='arn:aws:iam::aws:policy/AmazonS3FullAccess'
)
print(response)

Using AWS CLI, we can run below command

mahesh@mahesh:~$ aws iam detach-group-policy \
> --group-name 'admin' \
> --policy-arn 'arn:aws:iam::aws:policy/AdministratorAccess'

Deleting IAM group

In the last group operation of this article, we are going to learn how to delete the IAM group. Before deleting any group, we need to remove all members from that group and detach all policies attached to that group. Then only we will be able to delete the IAM group.

import boto3

#delete group using client
iam = boto3.client('iam') # IAM low level client object

#make sure group should not have any users
#and all attached policies have been removed
#before we can delete that group
response = iam.delete_group(
    GroupName='group1'
)

print(response)

#delete group using resource
iam = boto3.resource('iam')
group = iam.Group('group2')

#i have already removed users and attached polcies from group2
response = group.delete()
print(response)
# Deleting group in AWS CLI
mahesh@mahesh:~$ aws iam delete-group \
> --group-name 'group2'

Conclusion

In this tutorial on AWS IAM, we have gone through how to manage IAM group operations like create, add user, add/remove policy and delete using python and AWS CLI. I hope you have found it useful. See you in the next article, until then keep learning 🙂

.

Mahesh Mogal

I am passionate about Cloud, Data Analytics, Machine Learning, and Artificial Intelligence. I like to learn and try out new things. I have started blogging about my experience while learning these exciting technologies.

Stay Updated with Latest Blogs

Get latest blogs delivered to your mail directly.

Recent Posts

Sorting in Spark Dataframe

In this blog, we will learn how to sort rows in spark dataframe based on some column values.

Read More
Removing White Spaces From Data in Spark

White spaces can be a headache if not removed before processing data. We will learn how to remove spaces from data in spark using inbuilt functions.

Read More
Padding Data in Spark Dataframe

In this blog, we will learn how to use rpad and lpad functions to add padding to data in spark dataframe.

Read More

Leave a Reply

Your email address will not be published. Required fields are marked *

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram
Share via
Copy link
Powered by Social Snap