agent: |
KyqIZ8LMOnuC9qxXPYEfRemove/Delete an IAM Policy from an AWS IAM User
Remove/Delete an IAM Policy from 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 is used to detach managed IAM policies or delete inline policies from specific IAM users. This action is crucial for maintaining secure and appropriate access levels within AWS environments, ensuring compliance with best security practices.
inputs
outputs
import boto3
from botocore.exceptions import ClientError, NoCredentialsError, BotoCoreError
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
def remove_or_modify_policy(iam_client, user_name, policy_arn=None, inline_policy_name=None):
"""
Detach a managed IAM policy or delete an inline IAM policy from a specified AWS IAM user.
Args:
iam_client: An initialized Boto3 IAM client.
user_name: The name of the IAM user.
policy_arn: The ARN of the managed IAM policy to be detached.
inline_policy_name: The name of the inline IAM policy to be deleted.
The function checks if the user exists and whether the specified policies are attached or exist,
then proceeds with the appropriate action.
"""
try:
# Check if the user exists
iam_client.get_user(UserName=user_name)
if policy_arn:
# Detach managed policy if it is attached
attached_policies = iam_client.list_attached_user_policies(UserName=user_name)['AttachedPolicies']
if any(policy['PolicyArn'] == policy_arn for policy in attached_policies):
iam_client.detach_user_policy(UserName=user_name, PolicyArn=policy_arn)
print(f"Detached policy {policy_arn} from {user_name}")
else:
print(f"Policy {policy_arn} is not attached to {user_name}")
elif inline_policy_name:
# Delete inline policy if it exists
inline_policies = iam_client.list_user_policies(UserName=user_name)['PolicyNames']
if inline_policy_name in inline_policies:
iam_client.delete_user_policy(UserName=user_name, PolicyName=inline_policy_name)
print(f"Deleted inline policy {inline_policy_name} from {user_name}")
else:
print(f"Inline policy {inline_policy_name} does not exist for {user_name}")
except ClientError as e:
print(f"An AWS ClientError occurred: {e}")
except NoCredentialsError:
print("No AWS credentials available. Please configure them.")
except BotoCoreError as e:
print(f"A BotoCoreError occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
iam_client = boto3.client('iam',aws_access_key_id=access_key,aws_secret_access_key=secret_key)
# user_name = 'test_user'
# policy_arn_to_remove = 'arn:aws:iam::aws:policy/AdministratorAccess' # Example ARN
# inline_policy_name = 'your-inline-policy-name'
remove_or_modify_policy(iam_client, user_name, policy_arn=policy_arn_to_remove)
copied