Skip to content

How do I export a list of IAM Identity Center identities and their assignments?

6 minute read
2

I want to export a list of all AWS IAM Identity Center permission sets and their assigned principals across member accounts in AWS Organizations.

Short description

To generate reports of IAM Identity Center permission sets, use Python scripts. You can create either a JSON report of permission sets with their assigned principals or a .csv file of accounts with their permission set assignments.

Important:

Resolution

Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version.

Prerequisites:

Generate a report of permission sets with assigned principals

Complete the following steps:

  1. Save the following Python script with a .py extension, such as permission_sets_report.py:

    import boto3, json
    
    idstoreclient = boto3.client('identitystore')
    ssoadminclient = boto3.client('sso-admin')
    orgsclient= boto3.client('organizations')
    
    users={}
    groups={}
    permissionSets={}
    Accounts=[]
    
    Instances= (ssoadminclient.list_instances()).get('Instances')
    InstanceARN=Instances[0].get('InstanceArn')
    IdentityStoreId=Instances[0].get('IdentityStoreId')
    
    #Dictionary mapping User IDs to usernames
    def mapUserIDs():
        ListUsers=idstoreclient.list_users(IdentityStoreId=IdentityStoreId)
        ListOfUsers=ListUsers['Users']
        while 'NextToken' in ListUsers.keys():
            ListUsers=idstoreclient.list_users(IdentityStoreId=IdentityStoreId,NextToken=ListUsers['NextToken'])
            ListOfUsers.extend(ListUsers['Users'])
        for eachUser in ListOfUsers:
            users.update({eachUser.get('UserId'):eachUser.get('UserName')})
    mapUserIDs()
    
    #Dictionary mapping Group IDs to display names
    def mapGroupIDs():
        ListGroups=idstoreclient.list_groups(IdentityStoreId=IdentityStoreId)
        ListOfGroups=ListGroups['Groups']
        while 'NextToken' in ListGroups.keys():
            ListGroups=idstoreclient.list_groups(IdentityStoreId=IdentityStoreId,NextToken=ListGroups['NextToken'])
            ListOfGroups.extend(ListGroups['Groups'])
        for eachGroup in ListOfGroups:
            groups.update({eachGroup.get('GroupId'):eachGroup.get('DisplayName')})
    mapGroupIDs()
    
    #Dictionary mapping permission set ARNs to permission set names
    def mapPermissionSetIDs():
        ListPermissionSets=ssoadminclient.list_permission_sets(InstanceArn=InstanceARN)
        ListOfPermissionSets=ListPermissionSets['PermissionSets']
        while 'NextToken' in ListPermissionSets.keys():
            ListPermissionSets=ssoadminclient.list_permission_sets(InstanceArn=InstanceARN,NextToken=ListPermissionSets['NextToken'])
            ListOfPermissionSets.extend(ListPermissionSets['PermissionSets'])
        for eachPermissionSet in ListOfPermissionSets:
            permissionSetDescription=ssoadminclient.describe_permission_set(InstanceArn=InstanceARN,PermissionSetArn=eachPermissionSet)
            permissionSetDetails=permissionSetDescription.get('PermissionSet')
            permissionSets.update({permissionSetDetails.get('PermissionSetArn'):permissionSetDetails.get('Name')})
    mapPermissionSetIDs()
    
    #Listing Permissionsets provisioned to an account
    def GetPermissionSetsProvisionedToAccount(AccountID):
        ListOfPermissionSetsProvisionedToAccount=[]
        PermissionSetsProvisionedToAccount=ssoadminclient.list_permission_sets_provisioned_to_account(InstanceArn=InstanceARN,AccountId=AccountID)
        try:
            ListOfPermissionSetsProvisionedToAccount = PermissionSetsProvisionedToAccount['PermissionSets']
            while 'NextToken' in PermissionSetsProvisionedToAccount.keys():
                PermissionSetsProvisionedToAccount=ssoadminclient.list_permission_sets_provisioned_to_account(InstanceArn=InstanceARN,AccountId=AccountID,NextToken=PermissionSetsProvisionedToAccount['NextToken'])
                ListOfPermissionSetsProvisionedToAccount.extend(PermissionSetsProvisionedToAccount['PermissionSets'])
            return(ListOfPermissionSetsProvisionedToAccount)
        except:
            return(ListOfPermissionSetsProvisionedToAccount)
    
    
    #To retrieve the assignment of each permissionset/user/group/account assignment
    def ListAccountAssignments(AccountID):
        PermissionSetsList=GetPermissionSetsProvisionedToAccount(AccountID)
        Assignments=[]
        for permissionSet in PermissionSetsList:
            AccountAssignments=ssoadminclient.list_account_assignments(InstanceArn=InstanceARN,AccountId=AccountID,PermissionSetArn=permissionSet)
            Assignments.extend(AccountAssignments['AccountAssignments'])
            while 'NextToken' in AccountAssignments.keys():
                AccountAssignments=ssoadminclient.list_aaccount_assignments(InstanceArn=InstanceARN,AccountId=AccountID,PermissionSetArn=permissionSet,NextToken=AccountAssignments['NextToken'])
                Assignments.extend(AccountAssignments['AccountAssignments'])
        return(Assignments)
    
    #To list all the accounts in the organization
    def ListAccountsInOrganization():
        AccountsList=orgsclient.list_accounts()
        ListOfAccounts=AccountsList['Accounts']
        while 'NextToken' in AccountsList.keys():
            AccountsList=orgsclient.list_accounts(NextToken=AccountsList['NextToken'])
            ListOfAccounts.extend(AccountsList['Accounts'])
        for eachAccount in ListOfAccounts:
            Accounts.append(str(eachAccount.get('Id')))
        return(Accounts)
    
    #To translate set datatype to json
    class SetEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, set):
                return list(obj)
            return json.JSONEncoder.default(self, obj)
    
    def GetListOfAssignmentsForPermissionSets():
        ListOfAccountIDs=ListAccountsInOrganization()
        entries=[]
        PermissionSetListForAssignments={}
        for eachAccountID in ListOfAccountIDs:
            GetAccountAssignments=ListAccountAssignments(eachAccountID)
            for eachAssignment in GetAccountAssignments:
                if(permissionSets.get(eachAssignment.get('PermissionSetArn'))) not in PermissionSetListForAssignments.keys():
                    SetOfUsersandGroups={'Users':set(),'Groups':set()}
                    PermissionSetListForAssignments[permissionSets.get(eachAssignment.get('PermissionSetArn'))]=SetOfUsersandGroups
                SetOfUsersandGroups=PermissionSetListForAssignments.get(permissionSets.get(eachAssignment.get('PermissionSetArn')))
                if(eachAssignment.get('PrincipalType')=='GROUP'):
                    setOfGroups=SetOfUsersandGroups.get('Groups')
                    setOfGroups.add(groups.get(eachAssignment.get('PrincipalId')))
                    SetOfUsersandGroups.update({'Groups':setOfGroups})
                    PermissionSetListForAssignments.update({permissionSets.get(eachAssignment.get('PermissionSetArn')):SetOfUsersandGroups})
                else:
                    setOfUsers=SetOfUsersandGroups.get('Users')
                    setOfUsers.add(users.get(eachAssignment.get('PrincipalId')))
                    SetOfUsersandGroups.update({'Users':setOfUsers})
                    PermissionSetListForAssignments.update({permissionSets.get(eachAssignment.get('PermissionSetArn')):SetOfUsersandGroups})
        with open("AssignmentsForPermissionSets.json", "w") as outfile:
            json.dump(PermissionSetListForAssignments, outfile, cls=SetEncoder)
        print("Done!AssignmentsForPermissionSets.json generated successfully!")
    GetListOfAssignmentsForPermissionSets()

    Note: If you receive the "IndexError: list index out of range" error, then the script is in an AWS Region that isn't the Region where you configured IAM Identity Center.

  2. Run the Python script in a Terminal (macOS) or PowerShell (Windows) window.

The script creates a JSON file that's named AssignmentsForPermissionSets.json that contains your permission sets and their assigned principals.

Example output:

{  "AdministratorAccess": {    "Users": [
      "Charlie",
      "Ted"
    ],
    "Groups": [
      "Admins",
      "Developers"
    ]
  },
  "PowerUserAccess": {
    "Users": [
      "Chandler",
      "Joey"
    ],
    "Groups": [
      "Developers",
      "Testers"
    ]
  },
  "SystemAdministrator": {
    "Users": [
      "Sherlock"
    ],
    "Groups": [
      "DevOps"
    ]
  }
}

Note: If a permission set isn't in the report, then you didn't provision a permission set for the accounts.

Generate a report with the permission set assignments of accounts

Complete the following steps:

  1. Save the following Python script with a .py extension, such as account_assignments_report.py:

    import boto3, csv
    
    idstoreclient = boto3.client('identitystore')
    ssoadminclient = boto3.client('sso-admin')
    orgsclient= boto3.client('organizations')
    
    users={}
    groups={}
    permissionSets={}
    Accounts={}
    
    Instances= (ssoadminclient.list_instances()).get('Instances')
    InstanceARN=Instances[0].get('InstanceArn')
    IdentityStoreId=Instances[0].get('IdentityStoreId')
    
    
    #Dictionary mapping User IDs to usernames
    def mapUserIDs():
        ListUsers=idstoreclient.list_users(IdentityStoreId=IdentityStoreId)
        ListOfUsers=ListUsers['Users']
        while 'NextToken' in ListUsers.keys():
            ListUsers=idstoreclient.list_users(IdentityStoreId=IdentityStoreId,NextToken=ListUsers['NextToken'])
            ListOfUsers.extend(ListUsers['Users'])
        for eachUser in ListOfUsers:
            users.update({eachUser.get('UserId'):eachUser.get('UserName')})
    mapUserIDs()
    
    #Dictionary mapping Group IDs to display names
    def mapGroupIDs():
        ListGroups=idstoreclient.list_groups(IdentityStoreId=IdentityStoreId)
        ListOfGroups=ListGroups['Groups']
        while 'NextToken' in ListGroups.keys():
            ListGroups=idstoreclient.list_groups(IdentityStoreId=IdentityStoreId,NextToken=ListGroups['NextToken'])
            ListOfGroups.extend(ListGroups['Groups'])
        for eachGroup in ListOfGroups:
            groups.update({eachGroup.get('GroupId'):eachGroup.get('DisplayName')})
    mapGroupIDs()
    
    #Dictionary mapping permission set ARNs to permission set names
    def mapPermissionSetIDs():
        ListPermissionSets=ssoadminclient.list_permission_sets(InstanceArn=InstanceARN)
        ListOfPermissionSets=ListPermissionSets['PermissionSets']
        while 'NextToken' in ListPermissionSets.keys():
            ListPermissionSets=ssoadminclient.list_permission_sets(InstanceArn=InstanceARN,NextToken=ListPermissionSets['NextToken'])
            ListOfPermissionSets.extend(ListPermissionSets['PermissionSets'])
        for eachPermissionSet in ListOfPermissionSets:
            permissionSetDescription=ssoadminclient.describe_permission_set(InstanceArn=InstanceARN,PermissionSetArn=eachPermissionSet)
            permissionSetDetails=permissionSetDescription.get('PermissionSet')
            permissionSets.update({permissionSetDetails.get('PermissionSetArn'):permissionSetDetails.get('Name')})
    mapPermissionSetIDs()
    
    #Listing Permissionsets provisioned to an account
    def GetPermissionSetsProvisionedToAccount(AccountID):
        PermissionSetsProvisionedToAccount=ssoadminclient.list_permission_sets_provisioned_to_account(InstanceArn=InstanceARN,AccountId=AccountID)
        ListOfPermissionSetsProvisionedToAccount = PermissionSetsProvisionedToAccount['PermissionSets']
        while 'NextToken' in PermissionSetsProvisionedToAccount.keys():
            PermissionSetsProvisionedToAccount=ssoadminclient.list_permission_sets_provisioned_to_account(InstanceArn=InstanceARN,AccountId=AccountID,NextToken=PermissionSetsProvisionedToAccount['NextToken'])
            ListOfPermissionSetsProvisionedToAccount.extend(PermissionSetsProvisionedToAccount['PermissionSets'])    
        return(ListOfPermissionSetsProvisionedToAccount)
    
    #To retrieve the assignment of each permissionset/user/group/account assignment
    def ListAccountAssignments(AccountID):
        PermissionSetsList=GetPermissionSetsProvisionedToAccount(AccountID)
        Assignments=[]
        for permissionSet in PermissionSetsList:
            AccountAssignments=ssoadminclient.list_account_assignments(InstanceArn=InstanceARN,AccountId=AccountID,PermissionSetArn=permissionSet)
            Assignments.extend(AccountAssignments['AccountAssignments'])
            while 'NextToken' in AccountAssignments.keys():
                AccountAssignments=ssoadminclient.list_aaccount_assignments(InstanceArn=InstanceARN,AccountId=AccountID,PermissionSetArn=permissionSet,NextToken=AccountAssignments['NextToken'])
                Assignments.extend(AccountAssignments['AccountAssignments'])
        return(Assignments)
    
    
    #To list all the accounts in the organization
    def ListAccountsInOrganization():
        AccountsList=orgsclient.list_accounts()
        ListOfAccounts=AccountsList['Accounts']
        while 'NextToken' in AccountsList.keys():
            AccountsList=orgsclient.list_accounts(NextToken=AccountsList['NextToken'])
            ListOfAccounts.extend(AccountsList['Accounts'])
        for eachAccount in ListOfAccounts:
            Accounts.update({eachAccount.get('Id'):eachAccount.get('Name')})
        return(Accounts)
    
    def WriteToExcel():
        Accounts=ListAccountsInOrganization()
        ListOfAccountIDs=list(Accounts.keys())
        entries=[]
        for eachAccountID in ListOfAccountIDs:
            try:
                GetAccountAssignments=ListAccountAssignments(eachAccountID)
                for eachAssignment in GetAccountAssignments:
                    entry=[]
                    entry.append(eachAssignment.get('AccountId'))
                    entry.append(Accounts.get(eachAssignment.get('AccountId')))
                    entry.append(permissionSets.get(eachAssignment.get('PermissionSetArn')))
                    entry.append(eachAssignment.get('PrincipalType'))
                    if(eachAssignment.get('PrincipalType')=='GROUP'):
                        entry.append(groups.get(eachAssignment.get('PrincipalId')))
                    else:
                        entry.append(users.get(eachAssignment.get('PrincipalId')))
                    entries.append(entry)
            except:
                continue
        filename = "IdentityStoreReport.csv"
        headers=['Account ID', 'Account Name', 'Permission Set','Principal Type', 'Principal']
    
        with open(filename, 'w') as report:
            csvwriter = csv.writer(report)
            csvwriter.writerow(headers)
            csvwriter.writerows(entries)
        print("Done! 'IdentityStoreReport.csv' report is generated successfully!")
    WriteToExcel()
  2. Run the Python script in a Terminal (macOS) or PowerShell (Windows) window.

The script creates a .csv file that's named IdentityStoreReport.csv that contains your account assignments. Your system saves the .csv file in the same directory as the permission sets report.

Example .csv file output:

Account IDAccount NamePermission SetPrincipal TypePrincipal
123456789012DevelopmentPowerUserAccessGROUPDevelopers
123456789012DevelopmentPowerUserAccessUSERRoss
123456789012DevelopmentAdministratorAccessUSERPhoebe
123456789012DevelopmentSystemAdministratorUSERJake
345678901234ProductionAdministratorAccessGROUPAdmins
345678901234ProductionAdministratorAccessGROUPTesting
901234567890StagingPowerUserAccessGROUPTesting
901234567890StagingAdministratorAccessGROUPClient
901234567890StagingPowerUserAccessUSERGina
901234567890StagingPowerUserAccessGROUPAdmins

Note: If an account isn't in the report, then you didn't provision permission sets for the account.

AWS OFFICIALUpdated 9 months ago
12 Comments

Thanks for the useful scripts!

In each of the scripts, there is a typo in the function ListAccountsInOrganization.

In the while loop, the ListOfAccounts var should be updated by either the += operator or the extend method, instead of just =, so that full list of accounts doesn't just include whatever is on the last set retrieved from the NextToken list.

The updated line is here:

def ListAccountsInOrganization():
    AccountsList=orgsclient.list_accounts()
    ListOfAccounts=AccountsList['Accounts']
    while 'NextToken' in AccountsList.keys():
        AccountsList=orgsclient.list_accounts(NextToken=AccountsList['NextToken'])
        ListOfAccounts+=AccountsList['Accounts']
    for eachAccount in ListOfAccounts:
        Accounts.update({eachAccount.get('Id'):eachAccount.get('Name')})
    return(Accounts)
replied 3 years ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

AWS
MODERATOR
replied 3 years ago

Incredible work!! Just what I was looking for. Would really appreciate a GUI feature but these scripts saved the day for now.

replied 3 years ago

Will have a go at fixing myself but I'm no Python expert

Each script is generating an error for me

File "/Users/mark.lloyd/report2.py", line 75 def ListOfAccounts=AccountsList['Accounts']: ^ SyntaxError: expected '('

replied 3 years ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

AWS
EXPERT
replied 3 years ago

Thanks for the article. Looks like the output of the second script is somehow being limited, I don't get full list of permission sets in all accounts.

replied 2 years ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

AWS
EXPERT
replied 2 years ago

Getting the below error while executing the script

python3 iamuserlist.py
Traceback (most recent call last):
  File "/Users/shoaibtaqi/iamuserlist.py", line 13, in <module>
    InstanceARN=Instances[0].get('InstanceArn')
                ~~~~~~~~~^^^
IndexError: list index out of range
replied 2 years ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

AWS
MODERATOR
replied 2 years ago

Getting the same error as Stagi File "/home/ec2-user/iamorgexporter.py", line 13, in <module> InstanceARN=Instances[0].get('InstanceArn') IndexError: list index out of range

replied 2 years ago

It appears the boto3 client calls have changed. Is there an updated and verified working version of this script?

replied a year ago

wish there was a simple way to link groups so that a query for sherlock would return groups that sherlock is a member of.

  "SystemAdministrator": {
    "Users": [],
    "Groups": [
      "DevOps"
    ]
  }
replied a year ago