Attach a managed policy to an IAM user
📑 On this page
Part 98 of AWS from Zero. This lesson changes or inspects one IAM concept so the permission model stays understandable.
What we are learning
Attaching a policy makes its allowed actions available to the user, subject to explicit denies and other permission controls.
Before you run it
USER_NAME="aws-zero-learner"
POLICY_ARN="arn:aws:iam::123456789012:policy/AwsZeroListBuckets"Review the exact default policy document before attachment.
The command
aws iam attach-user-policy \
--user-name "$USER_NAME" \
--policy-arn "$POLICY_ARN"IAM writes can take a short time to propagate. Inspect the resource after every change.
Inspect the result
aws iam list-attached-user-policies \
--user-name "$USER_NAME" \
--query "AttachedPolicies[?PolicyArn=='$POLICY_ARN']"Read the returned ARN, path, IDs, and attachment state instead of checking only the command exit code.
One tiny variation
aws iam attach-group-policy \
--group-name "$GROUP_NAME" \
--policy-arn "$POLICY_ARN"Group attachment shares the policy with all current and future group members.
Common mistake
Do not attach both directly and through a group without a reason. Duplicate allow paths make reviews noisier even though they do not grant more than the same allow.
Cleanup
aws iam detach-user-policy \
--user-name "$USER_NAME" \
--policy-arn "$POLICY_ARN"Detach the direct user policy. If you tried the group variation, detach that separately.
Next, we will learn Detach a managed policy from an IAM user.