# 通过Identity Store API大规模管理和审计 AWS IAM 身份中心的用户和组操作

Here's a Python script that reads user and group information from a CSV file and creates users and groups in AWS IAM Identity Store:

{% hint style="info" %}
Replace '/Your/File/Path/users.csv' with your file path in the python code
{% endhint %}

```python
import boto3
import csv
from botocore.exceptions import ClientError

def create_identity_store_user(identity_store_client, identity_store_id, user_data):
    """
    Create a user in the IAM Identity Store
    """
    try:
        response = identity_store_client.create_user(
            IdentityStoreId=identity_store_id,
            UserName=user_data['userName'],
            Name={
                'FamilyName': user_data['lastName'],
                'GivenName': user_data['firstName']
            },
            DisplayName=user_data['displayName'],
            Emails=[
                {
                    'Value': user_data['emailAddress'],
                    'Primary': True
                }
            ]
        )
        print(f"Created user: {user_data['userName']}")
        return response['UserId']
    except ClientError as e:
        if e.response['Error']['Code'] == 'ConflictException':
            print(f"User {user_data['userName']} already exists")
            # Get existing user ID
            response = identity_store_client.list_users(
                IdentityStoreId=identity_store_id,
                Filters=[{
                    'AttributePath': 'UserName',
                    'AttributeValue': user_data['userName']
                }]
            )
            return response['Users'][0]['UserId']
        else:
            print(f"Error creating user {user_data['userName']}: {e}")
            return None

def create_group(identity_store_client, identity_store_id, group_name):
    """
    Create a group in the IAM Identity Store
    """
    try:
        response = identity_store_client.create_group(
            IdentityStoreId=identity_store_id,
            DisplayName=group_name,
            Description=f"Group for {group_name}"
        )
        print(f"Created group: {group_name}")
        return response['GroupId']
    except ClientError as e:
        if e.response['Error']['Code'] == 'ConflictException':
            print(f"Group {group_name} already exists")
            # Get existing group ID
            response = identity_store_client.list_groups(
                IdentityStoreId=identity_store_id,
                Filters=[{
                    'AttributePath': 'DisplayName',
                    'AttributeValue': group_name
                }]
            )
            return response['Groups'][0]['GroupId']
        else:
            print(f"Error creating group {group_name}: {e}")
            return None

def add_user_to_group(identity_store_client, identity_store_id, user_id, group_id):
    """
    Add a user to a group in the IAM Identity Store
    """
    try:
        identity_store_client.create_group_membership(
            IdentityStoreId=identity_store_id,
            GroupId=group_id,
            MemberId={
                'UserId': user_id
            }
        )
        print(f"Added user {user_id} to group {group_id}")
    except ClientError as e:
        if e.response['Error']['Code'] == 'ConflictException':
            print(f"User {user_id} is already a member of group {group_id}")
        else:
            print(f"Error adding user to group: {e}")

def main():
    # Initialize AWS clients
    identity_store_client = boto3.client('identitystore')
    
    # Get the Identity Store ID
    sso_admin_client = boto3.client('sso-admin')
    identity_store = sso_admin_client.list_instances()['Instances'][0]
    identity_store_id = identity_store['IdentityStoreId']

    # Read CSV file
    with open('/Your/File/Path/users.csv', 'r') as file:
        csv_reader = csv.DictReader(file)
        
        # Track created groups
        created_groups = {}
        
        for row in csv_reader:
            # Create user
            user_id = create_identity_store_user(identity_store_client, identity_store_id, row)
            
            if user_id and row['withinGroup']:
                # Create group if it doesn't exist
                if row['withinGroup'] not in created_groups:
                    group_id = create_group(identity_store_client, identity_store_id, row['withinGroup'])
                    created_groups[row['withinGroup']] = group_id
                
                # Add user to group
                if created_groups[row['withinGroup']]:
                    add_user_to_group(
                        identity_store_client,
                        identity_store_id,
                        user_id,
                        created_groups[row['withinGroup']]
                    )

if __name__ == "__main__":
    main()
```

To use this script, you'll need:

1. A CSV file named `users.csv` with the following columns:
   * firstName
   * lastName
   * userName
   * displayName
   * emailAddress
   * withinGroup
2. AWS credentials configured with appropriate permissions to manage IAM Identity Store
3. replace '/Your/File/Path/users.csv' with your  file path in the python code

Example CSV format:

```csv
firstName,lastName,userName,displayName,emailAddress,withinGroup
John,Doe,johndoe,John Doe,john.doe@example.com,Developers
Jane,Smith,janesmith,Jane Smith,jane.smith@example.com,Administrators
```

To run the script:

1. Install required dependencies:

```bash
pip install boto3
```

2. Make sure you have AWS credentials configured (either through AWS CLI or environment variables)
3. Run the script:

```bash
python script.py
```

The script will:

1. Read the CSV file
2. Create users in the IAM Identity Store
3. Create groups if they don't exist
4. Add users to their respective groups

Error handling is included for:

* Duplicate users/groups
* AWS API errors
* Basic validation

Important notes:

* Make sure you have the necessary permissions in AWS to perform these operations
* The script assumes you have only one Identity Store instance
* The script will skip creating duplicates but will still try to add users to groups
* Error handling is implemented for common scenarios

Customize the script based on your specific requirements, such as:

* Adding more error handling
* Implementing logging
* Adding more user attributes
* Implementing validation for input data
* Adding support for multiple Identity Stores

Remember to:

1. Have the correct AWS credentials configured
2. Have the necessary permissions to manage IAM Identity Store
3. Have a properly formatted CSV file
4. Install the required boto3 library

The script will now properly create users, groups, and add users to their respective groups in the IAM Identity Store.
