AWS SDK for Ruby
Developer Guide

Working with IAM Policies

An IAM policy is a document that specifies one or more permissions. For more information about IAM policies, see Overview of IAM Policies.

In this example, you use the AWS SDK for Ruby with IAM to:

  1. Create a policy, using Aws::IAM::Client#create_policy.

  2. Get information about the policy, using Aws::IAM::Client#get_policy.

  3. Attach the policy to a role, using Aws::IAM::Client#attach_role_policy.

  4. List policies attached to the role, using Aws::IAM::Client#list_attached_role_policies.

  5. Detach the policy from the role, using Aws::IAM::Client#detach_role_policy.

Prerequisites

Before running the example code, you need to install and configure the AWS SDK for Ruby, as described in:

You will also need to create the role (my-role) specified in the script. You can do this in the IAM console.

Example

require 'aws-sdk-iam' # v2: require 'aws-sdk' iam = Aws::IAM::Client.new(region: 'us-east-1') role_name = "my-role" policy_name = "my-policy" policy_document = { "Version" => "2012-10-17", "Statement" => [ { "Effect" => "Allow", "Action" => "s3:ListAllMyBuckets", "Resource" => "arn:aws:s3:::*" } ] }.to_json # Create a policy. puts "Creating policy..." create_policy_response = iam.create_policy({ policy_name: policy_name, policy_document: policy_document }) policy_arn = create_policy_response.policy.arn # Get information about the policy. get_policy_response = iam.get_policy({ policy_arn: policy_arn }) puts "\nCreated policy, ID = #{get_policy_response.policy.policy_id}" # Attach the policy to a role. puts "\nAttaching policy to role..." iam.attach_role_policy({ role_name: role_name, policy_arn: policy_arn }) # List policies attached to the role. puts "\nAttached role policy ARNs..." iam.list_attached_role_policies({ role_name: role_name }).attached_policies.each do |attached_policy| puts " #{attached_policy.policy_arn}" end # Detach the policy from the role. puts "\nDetaching role policy..." iam.detach_role_policy({ role_name: role_name, policy_arn: policy_arn })

On this page: