0
0
AwsHow-ToBeginner · 3 min read

How to Attach a Policy to an AWS Role: Simple Steps

To attach a policy to an AWS IAM role, use the aws iam attach-role-policy command with the role name and policy ARN, or use the AWS Management Console to add the policy under the role's permissions tab. This links the policy's permissions to the role, allowing it to perform actions defined by the policy.
📐

Syntax

The command to attach a policy to a role in AWS CLI is:

aws iam attach-role-policy --role-name <role-name> --policy-arn <policy-arn>

Here:

  • --role-name is the name of the IAM role you want to attach the policy to.
  • --policy-arn is the Amazon Resource Name (ARN) of the policy you want to attach.
bash
aws iam attach-role-policy --role-name MyExampleRole --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
💻

Example

This example shows how to attach the AWS managed policy AmazonS3ReadOnlyAccess to a role named MyExampleRole using AWS CLI.

bash
aws iam attach-role-policy --role-name MyExampleRole --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
Output
No output if successful; the policy is attached to the role.
⚠️

Common Pitfalls

Common mistakes when attaching policies to roles include:

  • Using the wrong role-name or misspelling it causes errors.
  • Using an incorrect or incomplete policy-arn will fail the command.
  • Trying to attach a policy that is already attached does nothing but does not error.
  • Not having sufficient permissions to attach policies results in access denied errors.

Always verify the role name and policy ARN before running the command.

bash
aws iam attach-role-policy --role-name WrongRoleName --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

# Correct usage:
aws iam attach-role-policy --role-name MyExampleRole --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
📊

Quick Reference

ParameterDescription
--role-nameName of the IAM role to attach the policy to
--policy-arnARN of the IAM policy to attach
Example policy ARNarn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
Commandaws iam attach-role-policy --role-name MyRole --policy-arn arn:aws:iam::aws:policy/PolicyName

Key Takeaways

Use the AWS CLI command 'aws iam attach-role-policy' with correct role name and policy ARN to attach a policy.
Double-check role names and policy ARNs to avoid errors.
You can also attach policies via the AWS Management Console under the IAM role's permissions tab.
Lack of permissions to attach policies will cause access denied errors.
Attaching a policy that is already attached has no effect but does not cause errors.