Sign in
agent:

Working with AWS IAM Users

There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

In AWS, IAM (Identity and Access Management) users are pivotal for ensuring granular access control to resources. The creation process involves defining a unique username and, optionally, assigning specific permissions or attaching policies that dictate what actions the user can perform. For added security, a login profile with a password can be set up, allowing the user to access the AWS Management Console. Conversely, when an IAM user is no longer needed or poses a security risk, it's crucial to delete them. This involves detaching all associated policies, removing any login profiles, and finally, deleting the user itself, ensuring that residual permissions don't linger in the system.

  1. 1

    List all AWS IAM Users

    There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

    This lists all IAM users in an AWS account, providing key details like usernames, user IDs, and creation dates. Essential for managing permissions and auditing access, this function supports security and compliance protocols by offering a clear view of user entities and their access levels. It's instrumental in enforcing security policies and the principle of least privilege in AWS resource access management.

    import boto3 import botocore.exceptions creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] # Initialize the IAM client iam_client = boto3.client('iam',aws_access_key_id=access_key,aws_secret_access_key=secret_key) try: # Create a paginator for the list_users operation paginator = iam_client.get_paginator('list_users') # Use the paginator to paginate through the users table = context.newtable() table.title = "User list" table.num_cols = 3 table.num_rows = 1 table.has_header_row = True rownum = 0 table.setval(rownum, 0, "User name") table.setval(rownum, 1, "User ID") table.setval(rownum, 2, "Created on") for page in paginator.paginate(): users = page['Users'] table.num_rows += len(page['Users']) # Output user details if users: # print("List of IAM Users:") for user in users: rownum += 1 # print(f"Username: {user['UserName']}, User ID: {user['UserId']}, Created On: {user['CreateDate']}") table.setval(rownum, 0, user['UserName']) table.setval(rownum, 1, user['UserId']) table.setval(rownum, 2, user['CreateDate']) else: print("No IAM users found in this page.") # Handle specific exceptions except botocore.exceptions.NoCredentialsError: print("Credentials not available") except botocore.exceptions.PartialCredentialsError: print("Incomplete credentials provided") except botocore.exceptions.SSLError: print("SSL connection could not be established. Ensure your network allows SSL connections to AWS services") except botocore.exceptions.EndpointConnectionError: print("Unable to connect to the endpoint. Check your AWS configuration and network settings") except botocore.exceptions.ClientError as e: print(f"Unexpected error occurred accessing AWS: {e}") # Handle general exceptions except Exception as e: print(f"An unhandled error occurred: {str(e)}")
    copied
    1
  2. 2

    Create an AWS IAM user

    There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

    This task creates an IAM user which is an identity with specific permissions to access and manage AWS resources. This allows for fine-grained access control by assigning individualized permissions or roles to each user, rather than using root account credentials. Creating an IAM user is essential for securely managing access to AWS services and resources.

    import boto3 creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] # Initialize the AWS clients for IAM (Identity and Access Management) and STS (Security Token Service) iam = boto3.client('iam',aws_access_key_id=access_key,aws_secret_access_key=secret_key) sts = boto3.client('sts',aws_access_key_id=access_key,aws_secret_access_key=secret_key) def validate_password(password): """ Validate the password against AWS's default password policy. AWS's password policy typically requires the following: - A minimum length (e.g., 8 characters) - At least one uppercase letter - At least one lowercase letter - At least one number - At least one special character from a predefined set """ # Check each requirement and return False if any are not met if (len(password) < 8 or not any(char.isdigit() for char in password) or not any(char.isupper() for char in password) or not any(char.islower() for char in password) or not any(char in '!@#$%^&*()-+=' for char in password)): return False return True def create_iam_user(user_name=None, password=None): """ Creates an IAM user and assigns a login profile (console access). """ # Preliminary check: Ensure both username and password are provided if not user_name or not password: print("Error: Both username and password are required.") return # Validate the provided password against AWS's requirements if not validate_password(password): print("Error: The provided password doesn't meet AWS's default password policy.") return try: # Check if the IAM user already exists iam.get_user(UserName=user_name) print(f"Error: IAM user {user_name} already exists.") return except iam.exceptions.NoSuchEntityException: # This is the expected exception if the user does not exist, so we can proceed to create one pass # Attempt to create the IAM user try: response = iam.create_user(UserName=user_name) print(f"IAM user {user_name} created successfully!") except iam.exceptions.EntityAlreadyExistsException: print(f"Error: IAM user {user_name} already exists.") return except Exception as e: print(f"An error occurred while creating IAM user {user_name}: {e}") return # Attempt to create a login profile, which allows the user to access the AWS Management Console try: iam.create_login_profile(UserName=user_name, Password=password) print(f"Login profile created for user {user_name}!") # Get the AWS ARN (Amazon Resource Name) of the entity making the call. Useful for audit purposes. caller_identity = sts.get_caller_identity() print(f"IAM user {user_name} created by {caller_identity['Arn']}") except Exception as e: print(f"An error occurred while creating a login profile for IAM user {user_name}: {e}") ''' Define IAM user name and password user_name, password initialized in input parameters ''' user_name = locals().get('user_name', '') or '' password = locals().get('password', '') or '' if not user_name or not password: print("Please provide a valid user name and password.") else: create_iam_user(user_name, password) context.proceed = False
    copied
    2
  3. 3

    Attach Policies to an AWS IAM user

    There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

    In AWS, policies define how operations are allowed or denied. This task attaches policies to an IAM user which in turn sets permissions on what actions that user can and cannot perform within AWS services. Essentially, it's a way to control a user's access to AWS resources. Policies can be predefined by AWS, like managed policies, or custom-defined by users. By strategically attaching and detaching policies, AWS administrators can finely tune access permissions for individual IAM users or groups.

    import boto3 creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] # Initialize the IAM client for AWS iam = boto3.client('iam',aws_access_key_id=access_key,aws_secret_access_key=secret_key) def attach_policies_to_user(user_name, policy_arns=[]): """ Attaches a list of policies to an IAM user. Parameters: - user_name (str): The name of the IAM user. - policy_arns (list): List of policy ARNs to attach to the user. """ # Check if user_name is provided if not user_name: print("Error: Username is required to attach policies.") return # Check if any policies are provided if not policy_arns: print("Error: At least one policy ARN is required to attach to the user.") return # Attempt to attach each policy to the user for policy_arn in policy_arns: try: iam.attach_user_policy(UserName=user_name, PolicyArn=policy_arn) print(f"Successfully attached policy {policy_arn} to user {user_name}.") except Exception as e: print(f"An error occurred while attaching policy {policy_arn} to user {user_name}: {e}") # Define the IAM user name and the list of policy ARNs you want to attach # Note: You should replace 'user_name' and 'policy_arns_list' with your actual values. # user_name initialized in input parameters policy_arns_list = [ 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess', # Add more policy ARNs as needed ] # Call the function to attach the specified policies to the IAM user attach_policies_to_user(user_name, policy_arns_list) context.proceed = False
    copied
    3
  4. 4

    Delete an AWS IAM user

    There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

    This task deletes an IAM user in AWS which is a critical step in managing access to AWS resources. This process ensures that the user no longer has permission to perform actions or access resources. It involves several key steps: detaching all associated policies, removing any login profiles or access keys, and finally, deleting the user itself. This action is irreversible, and once the user is deleted, they cannot access the AWS Management Console, AWS CLI, or API operations unless recreated. Properly removing users helps in maintaining a secure and tidy AWS environment, especially when individuals no longer require access or have changed roles.

    import boto3 creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] # Initialize the IAM and STS clients iam = boto3.client('iam',aws_access_key_id=access_key,aws_secret_access_key=secret_key) sts = boto3.client('sts',aws_access_key_id=access_key,aws_secret_access_key=secret_key) def delete_iam_user(username=None): """ Delete an IAM user and its associated resources. Parameters: - username (str, optional): The name of the IAM user to delete. """ # Step 0: Preliminary check if a username is provided if not username: print("Error: Username is required to delete an IAM user.") return # Step 1: Check if the user exists try: iam.get_user(UserName=username) except iam.exceptions.NoSuchEntityException: print(f"User {username} does not exist.") return except Exception as e: print(f"Error fetching details for IAM user {username}: {e}") return # Step 2: Delete access keys associated with the user try: # Fetching all the access keys associated with the user access_keys = iam.list_access_keys(UserName=username) # Iterate through each access key and delete them for key_metadata in access_keys['AccessKeyMetadata']: iam.delete_access_key(UserName=username, AccessKeyId=key_metadata['AccessKeyId']) print(f"Deleted access key {key_metadata['AccessKeyId']} for user {username}.") except Exception as e: print(f"Error deleting access keys for user {username}: {e}") # Step 3: Delete login profile for the user try: # Deleting the console access (login profile) of the user iam.delete_login_profile(UserName=username) print(f"Login profile for user {username} deleted successfully.") except iam.exceptions.NoSuchEntityException: print(f"No login profile found for user {username}.") except Exception as e: print(f"Error deleting login profile for user {username}: {e}") # Step 4: Detach all policies associated with the user # Using a paginator to handle users with a large number of attached policies paginator = iam.get_paginator('list_attached_user_policies') for page in paginator.paginate(UserName=username): for policy in page['AttachedPolicies']: try: # Detaching each policy from the user iam.detach_user_policy(UserName=username, PolicyArn=policy['PolicyArn']) print(f"Detached policy {policy['PolicyName']} from user {username}.") except Exception as e: print(f"Error detaching policy {policy['PolicyName']} from user {username}: {e}") # Step 5: Delete the IAM user try: # Deleting the user from AWS IAM iam.delete_user(UserName=username) print(f"IAM user {username} deleted successfully.") except Exception as e: print(f"Error deleting IAM user {username}: {e}") # Step 6: Post-deletion verification try: # Checking if the user still exists response = iam.get_user(UserName=username) print(f"User {username} still exists!") except iam.exceptions.NoSuchEntityException: print(f"Verified that user {username} has been deleted successfully.") # Fetching the identity of the caller for audit/tracking purposes caller_identity = sts.get_caller_identity() print(f"User {username} deleted by: {caller_identity['Arn']}") except Exception as e: print(f"Error verifying the deletion of IAM user {username}: {e}") ''' Specify the username of the IAM user you wish to delete user_to_delete initialized in input parameters ''' user_to_delete = locals().get('user_to_delete', '') or '' if not user_to_delete: print("Please provide a valid user name.") else: delete_iam_user(user_to_delete)
    copied
    4