Borislav Hadzhiev
Sun Sep 19 2021·3 min read
Photo by Holly Mandarich
IAM policies define permissions needed to access AWS resources and can be associated with roles, users and groups.
To attach an inline policy to an IAM role, we have to:
json
fileLet's define a policy that grants read permissions to all s3 buckets in an
account, create a file called read-s3.json
with the following content:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:Get*", "s3:List*" ], "Resource": "*" } ] }
Now that we've defined the inline policy, let's attach it to an IAM role. Open
your terminal in the directory where you stored the read-s3.json
file and run
the put-role-policy
command:
aws iam put-role-policy --role-name role-example --policy-name read-s3 --policy-document file://read-s3.json
To verify the inline policy has been attached to the role, run the list-role-policies command.
aws iam list-role-policies --role-name role-example
An AWS managed policy is one that's created and managed by AWS. These policies aim to provide permissions for the most common use cases.
To attach an AWS managed policy to an IAM role with the AWS CLI, use the attach-role-policy command.
Let's attach an AWS managed policy that grants dynamodb read actions to an IAM role:
aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess --role-name role-example
To verify a managed policy has been successfully attached to an IAM role, run the list-attached-role-policies command.
aws iam list-attached-role-policies --role-name role-example
Customer managed policies are created and managed by the user. They can be attached to multiple principal entities at the same time.
To attach a customer managed policy to a Role with AWS CLI, we have to:
Let's create a customer managed policy that grants read permissions to some
CloudWatch actions. Create a file called read-cloudwatch.json
with the
following content:
{ "Version": "2012-10-17", "Statement": [ { "Action": [ "logs:Get*", "logs:List*" ], "Effect": "Allow", "Resource": "*" } ] }
To create the customer managed policy, open your terminal in the directory
where the read-s3.json
file is stored and run the
create-policy
command.
aws iam create-policy --policy-name read-cloudwatch --policy-document file://read-cloudwatch.json
To attach a customer managed policy to a role, run the attach-role-policy command.
aws iam attach-role-policy --policy-arn "YOUR_POLICY_ARN" --role-name role-example
To verify the customer managed policy has been successfully attached to the role, run the list-attached-role-policies command.
aws iam list-attached-role-policies --role-name role-example
The output from the command shows both of our managed policies, the AWS managed one and the customer managed one.