Borislav Hadzhiev
Thu Sep 16 2021·3 min read
Photo by Will Wilson
IAM policies define specific permissions needed to access AWS resources and can be associated with IAM roles, users or groups.
To attach an inline policy to an IAM role, we have to:
json
file on the local file systemput-role-policy
commandThis is an example inline policy that grants read access to some CloudWatch actions:
{ "Version": "2012-10-17", "Statement": [ { "Action": [ "cloudwatch:Describe*", "cloudwatch:Get*", "cloudwatch:List*", ], "Effect": "Allow", "Resource": "*" } ] }
Now that we have the policy stored on the local file system, open your terminal
in the directory where you stored the file and run the put-role-policy
command:
aws iam put-role-policy --role-name YourRole --policy-name YourPolicy --policy-document file://read-cloudwatch.json
Notice that the inline-policy.json
file is prefixed with file://
in the
--policy-document
parameter.
--parameters
to an AWS CLI command, prefix the path with file://
for human-readable files or with fileb://
for binary (non human-readable) files.In the code snippet we assume that the terminal is located in the same directory
as the inline-policy.json
file, however if the terminal is in a different
directory we can still point to the file.
For example on linux
and macOS
you can use relative and absolute paths as
follows:
# relative path, navigate to directory aws iam put-role-policy --role-name YourRole --policy-name YourPolicy --policy-document file://./my-folder/read-cloudwatch.json # absolute path (notice 3 `/` characters in file:/// prefix) aws iam put-role-policy --role-name YourRole --policy-name YourPolicy --policy-document file:///home/john/read-bucket.json
On windows
you can specify a file://
prefix as follows:
aws iam put-role-policy --role-name YourRole --policy-name YourPolicy --policy-document file://C:\my-folder\read-bucket.json
To verify that the inline policy was successfully attached to the role, run the
list-role-policies
command:
aws iam list-role-policies --role-name YourRole
When using a json
file to attach inline policies to an IAM role, make sure
that the json
is syntactically correct.
json
file, the AWS CLI throws an error: (MalformedPolicyDocument) when calling the PutRolePolicy operation: Syntax errors in policy.To get the name of the policy that should get deleted from the role, run the
list-role-policies
command:
aws iam list-role-policies --role-name YourRole
To delete an inline policy, attached to an IAM Role, using the AWS CLI, run
the delete-role-policy
command.
aws iam delete-role-policy --role-name YourRole --policy-name YourPolicy
To verify the inline policy has been deleted from the role, run the
list-role-policies
command again:
aws iam list-role-policies --role-name YourRole