使用适用于 Ruby 的 SDK 的 IAM 示例 - Amazon 适用于 Ruby 的 SDK
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用适用于 Ruby 的 SDK 的 IAM 示例

以下代码示例向您展示了如何使用 with IAM 来执行操作和实现常见场景。 Amazon SDK for Ruby

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景 是展示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

操作

以下代码示例演示了如何使用 AttachRolePolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

此示例模块会列出、创建、附加和分离角色策略。

# Manages policies in AWS Identity and Access Management (IAM) class RolePolicyManager # Initialize with an AWS IAM client # # @param iam_client [Aws::IAM::Client] An initialized IAM client def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "PolicyManager" end # Creates a policy # # @param policy_name [String] The name of the policy # @param policy_document [Hash] The policy document # @return [String] The policy ARN if successful, otherwise nil def create_policy(policy_name, policy_document) response = @iam_client.create_policy( policy_name: policy_name, policy_document: policy_document.to_json ) response.policy.arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating policy: #{e.message}") nil end # Fetches an IAM policy by its ARN # @param policy_arn [String] the ARN of the IAM policy to retrieve # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found def get_policy(policy_arn) response = @iam_client.get_policy(policy_arn: policy_arn) policy = response.policy @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.") policy rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.") raise rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}") raise end # Attaches a policy to a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def attach_policy_to_role(role_name, policy_arn) @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to role: #{e.message}") false end # Lists policy ARNs attached to a role # # @param role_name [String] The name of the role # @return [Array<String>] List of policy ARNs def list_attached_policy_arns(role_name) response = @iam_client.list_attached_role_policies(role_name: role_name) response.attached_policies.map(&:policy_arn) rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing policies attached to role: #{e.message}") [] end # Detaches a policy from a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def detach_policy_from_role(role_name, policy_arn) @iam_client.detach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from role: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考AttachRolePolicy中的。

以下代码示例演示了如何使用 AttachUserPolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Attaches a policy to a user # # @param user_name [String] The name of the user # @param policy_arn [String] The Amazon Resource Name (ARN) of the policy # @return [Boolean] true if successful, false otherwise def attach_policy_to_user(user_name, policy_arn) @iam_client.attach_user_policy( user_name: user_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to user: #{e.message}") false end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考AttachUserPolicy中的。

以下代码示例演示了如何使用 CreateAccessKey

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

此示例模块会列出、创建、停用和删除访问密钥。

# Manages access keys for IAM users class AccessKeyManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "AccessKeyManager" end # Lists access keys for a user # # @param user_name [String] The name of the user. def list_access_keys(user_name) response = @iam_client.list_access_keys(user_name: user_name) if response.access_key_metadata.empty? @logger.info("No access keys found for user '#{user_name}'.") else response.access_key_metadata.map(&:access_key_id) end rescue Aws::IAM::Errors::NoSuchEntity => e @logger.error("Error listing access keys: cannot find user '#{user_name}'.") [] rescue StandardError => e @logger.error("Error listing access keys: #{e.message}") [] end # Creates an access key for a user # # @param user_name [String] The name of the user. # @return [Boolean] def create_access_key(user_name) response = @iam_client.create_access_key(user_name: user_name) access_key = response.access_key @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}") access_key rescue Aws::IAM::Errors::LimitExceeded => e @logger.error("Error creating access key: limit exceeded. Cannot create more.") nil rescue StandardError => e @logger.error("Error creating access key: #{e.message}") nil end # Deactivates an access key # # @param user_name [String] The name of the user. # @param access_key_id [String] The ID for the access key. # @return [Boolean] def deactivate_access_key(user_name, access_key_id) @iam_client.update_access_key( user_name: user_name, access_key_id: access_key_id, status: "Inactive" ) true rescue StandardError => e @logger.error("Error deactivating access key: #{e.message}") false end # Deletes an access key # # @param user_name [String] The name of the user. # @param access_key_id [String] The ID for the access key. # @return [Boolean] def delete_access_key(user_name, access_key_id) @iam_client.delete_access_key( user_name: user_name, access_key_id: access_key_id ) true rescue StandardError => e @logger.error("Error deleting access key: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考CreateAccessKey中的。

以下代码示例演示了如何使用 CreateAccountAlias

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

列出、创建和删除账户别名。

class IAMAliasManager # Initializes the IAM client and logger # # @param iam_client [Aws::IAM::Client] An initialized IAM client. def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger end # Lists available AWS account aliases. def list_aliases response = @iam_client.list_account_aliases if response.account_aliases.count.positive? @logger.info("Account aliases are:") response.account_aliases.each { |account_alias| @logger.info(" #{account_alias}") } else @logger.info("No account aliases found.") end rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing account aliases: #{e.message}") end # Creates an AWS account alias. # # @param account_alias [String] The name of the account alias to create. # @return [Boolean] true if the account alias was created; otherwise, false. def create_account_alias(account_alias) @iam_client.create_account_alias(account_alias: account_alias) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating account alias: #{e.message}") false end # Deletes an AWS account alias. # # @param account_alias [String] The name of the account alias to delete. # @return [Boolean] true if the account alias was deleted; otherwise, false. def delete_account_alias(account_alias) @iam_client.delete_account_alias(account_alias: account_alias) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting account alias: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考CreateAccountAlias中的。

以下代码示例演示了如何使用 CreatePolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

此示例模块会列出、创建、附加和分离角色策略。

# Manages policies in AWS Identity and Access Management (IAM) class RolePolicyManager # Initialize with an AWS IAM client # # @param iam_client [Aws::IAM::Client] An initialized IAM client def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "PolicyManager" end # Creates a policy # # @param policy_name [String] The name of the policy # @param policy_document [Hash] The policy document # @return [String] The policy ARN if successful, otherwise nil def create_policy(policy_name, policy_document) response = @iam_client.create_policy( policy_name: policy_name, policy_document: policy_document.to_json ) response.policy.arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating policy: #{e.message}") nil end # Fetches an IAM policy by its ARN # @param policy_arn [String] the ARN of the IAM policy to retrieve # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found def get_policy(policy_arn) response = @iam_client.get_policy(policy_arn: policy_arn) policy = response.policy @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.") policy rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.") raise rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}") raise end # Attaches a policy to a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def attach_policy_to_role(role_name, policy_arn) @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to role: #{e.message}") false end # Lists policy ARNs attached to a role # # @param role_name [String] The name of the role # @return [Array<String>] List of policy ARNs def list_attached_policy_arns(role_name) response = @iam_client.list_attached_role_policies(role_name: role_name) response.attached_policies.map(&:policy_arn) rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing policies attached to role: #{e.message}") [] end # Detaches a policy from a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def detach_policy_from_role(role_name, policy_arn) @iam_client.detach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from role: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考CreatePolicy中的。

以下代码示例演示了如何使用 CreateRole

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Creates a role and attaches policies to it. # # @param role_name [String] The name of the role. # @param assume_role_policy_document [Hash] The trust relationship policy document. # @param policy_arns [Array<String>] The ARNs of the policies to attach. # @return [String, nil] The ARN of the new role if successful, or nil if an error occurred. def create_role(role_name, assume_role_policy_document, policy_arns) response = @iam_client.create_role( role_name: role_name, assume_role_policy_document: assume_role_policy_document.to_json ) role_arn = response.role.arn policy_arns.each do |policy_arn| @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) end role_arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating role: #{e.message}") nil end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考CreateRole中的。

以下代码示例演示了如何使用 CreateServiceLinkedRole

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Creates a service-linked role # # @param service_name [String] The service name to create the role for. # @param description [String] The description of the service-linked role. # @param suffix [String] Suffix for customizing role name. # @return [String] The name of the created role def create_service_linked_role(service_name, description, suffix) response = @iam_client.create_service_linked_role( aws_service_name: service_name, description: description, custom_suffix: suffix,) role_name = response.role.role_name @logger.info("Created service-linked role #{role_name}.") role_name rescue Aws::Errors::ServiceError => e @logger.error("Couldn't create service-linked role for #{service_name}. Here's why:") @logger.error("\t#{e.code}: #{e.message}") raise end

以下代码示例演示了如何使用 CreateUser

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Creates a user and their login profile # # @param user_name [String] The name of the user # @param initial_password [String] The initial password for the user # @return [String, nil] The ID of the user if created, or nil if an error occurred def create_user(user_name, initial_password) response = @iam_client.create_user(user_name: user_name) @iam_client.wait_until(:user_exists, user_name: user_name) @iam_client.create_login_profile( user_name: user_name, password: initial_password, password_reset_required: true ) @logger.info("User '#{user_name}' created successfully.") response.user.user_id rescue Aws::IAM::Errors::EntityAlreadyExists @logger.error("Error creating user '#{user_name}': user already exists.") nil rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating user '#{user_name}': #{e.message}") nil end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考CreateUser中的。

以下代码示例演示了如何使用 DeleteAccessKey

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

此示例模块会列出、创建、停用和删除访问密钥。

# Manages access keys for IAM users class AccessKeyManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "AccessKeyManager" end # Lists access keys for a user # # @param user_name [String] The name of the user. def list_access_keys(user_name) response = @iam_client.list_access_keys(user_name: user_name) if response.access_key_metadata.empty? @logger.info("No access keys found for user '#{user_name}'.") else response.access_key_metadata.map(&:access_key_id) end rescue Aws::IAM::Errors::NoSuchEntity => e @logger.error("Error listing access keys: cannot find user '#{user_name}'.") [] rescue StandardError => e @logger.error("Error listing access keys: #{e.message}") [] end # Creates an access key for a user # # @param user_name [String] The name of the user. # @return [Boolean] def create_access_key(user_name) response = @iam_client.create_access_key(user_name: user_name) access_key = response.access_key @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}") access_key rescue Aws::IAM::Errors::LimitExceeded => e @logger.error("Error creating access key: limit exceeded. Cannot create more.") nil rescue StandardError => e @logger.error("Error creating access key: #{e.message}") nil end # Deactivates an access key # # @param user_name [String] The name of the user. # @param access_key_id [String] The ID for the access key. # @return [Boolean] def deactivate_access_key(user_name, access_key_id) @iam_client.update_access_key( user_name: user_name, access_key_id: access_key_id, status: "Inactive" ) true rescue StandardError => e @logger.error("Error deactivating access key: #{e.message}") false end # Deletes an access key # # @param user_name [String] The name of the user. # @param access_key_id [String] The ID for the access key. # @return [Boolean] def delete_access_key(user_name, access_key_id) @iam_client.delete_access_key( user_name: user_name, access_key_id: access_key_id ) true rescue StandardError => e @logger.error("Error deleting access key: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考DeleteAccessKey中的。

以下代码示例演示了如何使用 DeleteAccountAlias

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

列出、创建和删除账户别名。

class IAMAliasManager # Initializes the IAM client and logger # # @param iam_client [Aws::IAM::Client] An initialized IAM client. def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger end # Lists available AWS account aliases. def list_aliases response = @iam_client.list_account_aliases if response.account_aliases.count.positive? @logger.info("Account aliases are:") response.account_aliases.each { |account_alias| @logger.info(" #{account_alias}") } else @logger.info("No account aliases found.") end rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing account aliases: #{e.message}") end # Creates an AWS account alias. # # @param account_alias [String] The name of the account alias to create. # @return [Boolean] true if the account alias was created; otherwise, false. def create_account_alias(account_alias) @iam_client.create_account_alias(account_alias: account_alias) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating account alias: #{e.message}") false end # Deletes an AWS account alias. # # @param account_alias [String] The name of the account alias to delete. # @return [Boolean] true if the account alias was deleted; otherwise, false. def delete_account_alias(account_alias) @iam_client.delete_account_alias(account_alias: account_alias) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting account alias: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考DeleteAccountAlias中的。

以下代码示例演示了如何使用 DeleteRole

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Deletes a role and its attached policies. # # @param role_name [String] The name of the role to delete. def delete_role(role_name) begin # Detach and delete attached policies @iam_client.list_attached_role_policies(role_name: role_name).each do |response| response.attached_policies.each do |policy| @iam_client.detach_role_policy({ role_name: role_name, policy_arn: policy.policy_arn }) # Check if the policy is a customer managed policy (not AWS managed) unless policy.policy_arn.include?("aws:policy/") @iam_client.delete_policy({ policy_arn: policy.policy_arn }) @logger.info("Deleted customer managed policy #{policy.policy_name}.") end end end # Delete the role @iam_client.delete_role({ role_name: role_name }) @logger.info("Deleted role #{role_name}.") rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't detach policies and delete role #{role_name}. Here's why:") @logger.error("\t#{e.code}: #{e.message}") raise end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考DeleteRole中的。

以下代码示例演示了如何使用 DeleteServerCertificate

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

列出、更新和删除服务器证书。

class ServerCertificateManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "ServerCertificateManager" end # Creates a new server certificate. # @param name [String] the name of the server certificate # @param certificate_body [String] the contents of the certificate # @param private_key [String] the private key contents # @return [Boolean] returns true if the certificate was successfully created def create_server_certificate(name, certificate_body, private_key) @iam_client.upload_server_certificate({ server_certificate_name: name, certificate_body: certificate_body, private_key: private_key, }) true rescue Aws::IAM::Errors::ServiceError => e puts "Failed to create server certificate: #{e.message}" false end # Lists available server certificate names. def list_server_certificate_names response = @iam_client.list_server_certificates if response.server_certificate_metadata_list.empty? @logger.info("No server certificates found.") return end response.server_certificate_metadata_list.each do |certificate_metadata| @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}") end rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing server certificates: #{e.message}") end # Updates the name of a server certificate. def update_server_certificate_name(current_name, new_name) @iam_client.update_server_certificate( server_certificate_name: current_name, new_server_certificate_name: new_name ) @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.") true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error updating server certificate name: #{e.message}") false end # Deletes a server certificate. def delete_server_certificate(name) @iam_client.delete_server_certificate(server_certificate_name: name) @logger.info("Server certificate '#{name}' deleted.") true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting server certificate: #{e.message}") false end end

以下代码示例演示了如何使用 DeleteServiceLinkedRole

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Deletes a service-linked role. # # @param role_name [String] The name of the role to delete. def delete_service_linked_role(role_name) response = @iam_client.delete_service_linked_role(role_name: role_name) task_id = response.deletion_task_id check_deletion_status(role_name, task_id) rescue Aws::Errors::ServiceError => e handle_deletion_error(e, role_name) end private # Checks the deletion status of a service-linked role # # @param role_name [String] The name of the role being deleted # @param task_id [String] The task ID for the deletion process def check_deletion_status(role_name, task_id) loop do response = @iam_client.get_service_linked_role_deletion_status( deletion_task_id: task_id) status = response.status @logger.info("Deletion of #{role_name} #{status}.") break if %w[SUCCEEDED FAILED].include?(status) sleep(3) end end # Handles deletion error # # @param e [Aws::Errors::ServiceError] The error encountered during deletion # @param role_name [String] The name of the role attempted to delete def handle_deletion_error(e, role_name) unless e.code == "NoSuchEntity" @logger.error("Couldn't delete #{role_name}. Here's why:") @logger.error("\t#{e.code}: #{e.message}") raise end end

以下代码示例演示了如何使用 DeleteUser

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Deletes a user and their associated resources # # @param user_name [String] The name of the user to delete def delete_user(user_name) user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata user.each do |key| @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name }) @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.") end @iam_client.delete_user(user_name: user_name) @logger.info("Deleted user '#{user_name}'.") rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting user '#{user_name}': #{e.message}") end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考DeleteUser中的。

以下代码示例演示了如何使用 DeleteUserPolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Deletes a user and their associated resources # # @param user_name [String] The name of the user to delete def delete_user(user_name) user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata user.each do |key| @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name }) @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.") end @iam_client.delete_user(user_name: user_name) @logger.info("Deleted user '#{user_name}'.") rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting user '#{user_name}': #{e.message}") end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考DeleteUserPolicy中的。

以下代码示例演示了如何使用 DetachRolePolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

此示例模块会列出、创建、附加和分离角色策略。

# Manages policies in AWS Identity and Access Management (IAM) class RolePolicyManager # Initialize with an AWS IAM client # # @param iam_client [Aws::IAM::Client] An initialized IAM client def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "PolicyManager" end # Creates a policy # # @param policy_name [String] The name of the policy # @param policy_document [Hash] The policy document # @return [String] The policy ARN if successful, otherwise nil def create_policy(policy_name, policy_document) response = @iam_client.create_policy( policy_name: policy_name, policy_document: policy_document.to_json ) response.policy.arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating policy: #{e.message}") nil end # Fetches an IAM policy by its ARN # @param policy_arn [String] the ARN of the IAM policy to retrieve # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found def get_policy(policy_arn) response = @iam_client.get_policy(policy_arn: policy_arn) policy = response.policy @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.") policy rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.") raise rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}") raise end # Attaches a policy to a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def attach_policy_to_role(role_name, policy_arn) @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to role: #{e.message}") false end # Lists policy ARNs attached to a role # # @param role_name [String] The name of the role # @return [Array<String>] List of policy ARNs def list_attached_policy_arns(role_name) response = @iam_client.list_attached_role_policies(role_name: role_name) response.attached_policies.map(&:policy_arn) rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing policies attached to role: #{e.message}") [] end # Detaches a policy from a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def detach_policy_from_role(role_name, policy_arn) @iam_client.detach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from role: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考DetachRolePolicy中的。

以下代码示例演示了如何使用 DetachUserPolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Detaches a policy from a user # # @param user_name [String] The name of the user # @param policy_arn [String] The ARN of the policy to detach # @return [Boolean] true if the policy was successfully detached, false otherwise def detach_user_policy(user_name, policy_arn) @iam_client.detach_user_policy( user_name: user_name, policy_arn: policy_arn ) @logger.info("Policy '#{policy_arn}' detached from user '#{user_name}' successfully.") true rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Error detaching policy: Policy or user does not exist.") false rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from user '#{user_name}': #{e.message}") false end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考DetachUserPolicy中的。

以下代码示例演示了如何使用 GetAccountPasswordPolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Class to manage IAM account password policies class PasswordPolicyManager attr_accessor :iam_client, :logger def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "IAMPolicyManager" end # Retrieves and logs the account password policy def print_account_password_policy begin response = @iam_client.get_account_password_policy @logger.info("The account password policy is: #{response.password_policy.to_h}") rescue Aws::IAM::Errors::NoSuchEntity @logger.info("The account does not have a password policy.") rescue Aws::Errors::ServiceError => e @logger.error("Couldn't print the account password policy. Error: #{e.code} - #{e.message}") raise end end end

以下代码示例演示了如何使用 GetPolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Fetches an IAM policy by its ARN # @param policy_arn [String] the ARN of the IAM policy to retrieve # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found def get_policy(policy_arn) response = @iam_client.get_policy(policy_arn: policy_arn) policy = response.policy @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.") policy rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.") raise rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}") raise end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考GetPolicy中的。

以下代码示例演示了如何使用 GetRole

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Gets data about a role. # # @param name [String] The name of the role to look up. # @return [Aws::IAM::Role] The retrieved role. def get_role(name) role = @iam_client.get_role({ role_name: name, }).role puts("Got data for role '#{role.role_name}'. Its ARN is '#{role.arn}'.") rescue Aws::Errors::ServiceError => e puts("Couldn't get data for role '#{name}' Here's why:") puts("\t#{e.code}: #{e.message}") raise else role end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考GetRole中的。

以下代码示例演示了如何使用 GetUser

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Retrieves a user's details # # @param user_name [String] The name of the user to retrieve # @return [Aws::IAM::Types::User, nil] The user object if found, or nil if an error occurred def get_user(user_name) response = @iam_client.get_user(user_name: user_name) response.user rescue Aws::IAM::Errors::NoSuchEntity @logger.error("User '#{user_name}' not found.") nil rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error retrieving user '#{user_name}': #{e.message}") nil end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考GetUser中的。

以下代码示例演示了如何使用 ListAccessKeys

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

此示例模块会列出、创建、停用和删除访问密钥。

# Manages access keys for IAM users class AccessKeyManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "AccessKeyManager" end # Lists access keys for a user # # @param user_name [String] The name of the user. def list_access_keys(user_name) response = @iam_client.list_access_keys(user_name: user_name) if response.access_key_metadata.empty? @logger.info("No access keys found for user '#{user_name}'.") else response.access_key_metadata.map(&:access_key_id) end rescue Aws::IAM::Errors::NoSuchEntity => e @logger.error("Error listing access keys: cannot find user '#{user_name}'.") [] rescue StandardError => e @logger.error("Error listing access keys: #{e.message}") [] end # Creates an access key for a user # # @param user_name [String] The name of the user. # @return [Boolean] def create_access_key(user_name) response = @iam_client.create_access_key(user_name: user_name) access_key = response.access_key @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}") access_key rescue Aws::IAM::Errors::LimitExceeded => e @logger.error("Error creating access key: limit exceeded. Cannot create more.") nil rescue StandardError => e @logger.error("Error creating access key: #{e.message}") nil end # Deactivates an access key # # @param user_name [String] The name of the user. # @param access_key_id [String] The ID for the access key. # @return [Boolean] def deactivate_access_key(user_name, access_key_id) @iam_client.update_access_key( user_name: user_name, access_key_id: access_key_id, status: "Inactive" ) true rescue StandardError => e @logger.error("Error deactivating access key: #{e.message}") false end # Deletes an access key # # @param user_name [String] The name of the user. # @param access_key_id [String] The ID for the access key. # @return [Boolean] def delete_access_key(user_name, access_key_id) @iam_client.delete_access_key( user_name: user_name, access_key_id: access_key_id ) true rescue StandardError => e @logger.error("Error deleting access key: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考ListAccessKeys中的。

以下代码示例演示了如何使用 ListAccountAliases

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

列出、创建和删除账户别名。

class IAMAliasManager # Initializes the IAM client and logger # # @param iam_client [Aws::IAM::Client] An initialized IAM client. def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger end # Lists available AWS account aliases. def list_aliases response = @iam_client.list_account_aliases if response.account_aliases.count.positive? @logger.info("Account aliases are:") response.account_aliases.each { |account_alias| @logger.info(" #{account_alias}") } else @logger.info("No account aliases found.") end rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing account aliases: #{e.message}") end # Creates an AWS account alias. # # @param account_alias [String] The name of the account alias to create. # @return [Boolean] true if the account alias was created; otherwise, false. def create_account_alias(account_alias) @iam_client.create_account_alias(account_alias: account_alias) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating account alias: #{e.message}") false end # Deletes an AWS account alias. # # @param account_alias [String] The name of the account alias to delete. # @return [Boolean] true if the account alias was deleted; otherwise, false. def delete_account_alias(account_alias) @iam_client.delete_account_alias(account_alias: account_alias) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting account alias: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考ListAccountAliases中的。

以下代码示例演示了如何使用 ListAttachedRolePolicies

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

此示例模块会列出、创建、附加和分离角色策略。

# Manages policies in AWS Identity and Access Management (IAM) class RolePolicyManager # Initialize with an AWS IAM client # # @param iam_client [Aws::IAM::Client] An initialized IAM client def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "PolicyManager" end # Creates a policy # # @param policy_name [String] The name of the policy # @param policy_document [Hash] The policy document # @return [String] The policy ARN if successful, otherwise nil def create_policy(policy_name, policy_document) response = @iam_client.create_policy( policy_name: policy_name, policy_document: policy_document.to_json ) response.policy.arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating policy: #{e.message}") nil end # Fetches an IAM policy by its ARN # @param policy_arn [String] the ARN of the IAM policy to retrieve # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found def get_policy(policy_arn) response = @iam_client.get_policy(policy_arn: policy_arn) policy = response.policy @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.") policy rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.") raise rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}") raise end # Attaches a policy to a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def attach_policy_to_role(role_name, policy_arn) @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to role: #{e.message}") false end # Lists policy ARNs attached to a role # # @param role_name [String] The name of the role # @return [Array<String>] List of policy ARNs def list_attached_policy_arns(role_name) response = @iam_client.list_attached_role_policies(role_name: role_name) response.attached_policies.map(&:policy_arn) rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing policies attached to role: #{e.message}") [] end # Detaches a policy from a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def detach_policy_from_role(role_name, policy_arn) @iam_client.detach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from role: #{e.message}") false end end

以下代码示例演示了如何使用 ListGroups

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# A class to manage IAM operations via the AWS SDK client class IamGroupManager # Initializes the IamGroupManager class # @param iam_client [Aws::IAM::Client] An instance of the IAM client def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger end # Lists up to a specified number of groups for the account. # @param count [Integer] The maximum number of groups to list. # @return [Aws::IAM::Client::Response] def list_groups(count) response = @iam_client.list_groups(max_items: count) response.groups.each do |group| @logger.info("\t#{group.group_name}") end response rescue Aws::Errors::ServiceError => e @logger.error("Couldn't list groups for the account. Here's why:") @logger.error("\t#{e.code}: #{e.message}") raise end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考ListGroups中的。

以下代码示例演示了如何使用 ListPolicies

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

此示例模块会列出、创建、附加和分离角色策略。

# Manages policies in AWS Identity and Access Management (IAM) class RolePolicyManager # Initialize with an AWS IAM client # # @param iam_client [Aws::IAM::Client] An initialized IAM client def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "PolicyManager" end # Creates a policy # # @param policy_name [String] The name of the policy # @param policy_document [Hash] The policy document # @return [String] The policy ARN if successful, otherwise nil def create_policy(policy_name, policy_document) response = @iam_client.create_policy( policy_name: policy_name, policy_document: policy_document.to_json ) response.policy.arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating policy: #{e.message}") nil end # Fetches an IAM policy by its ARN # @param policy_arn [String] the ARN of the IAM policy to retrieve # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found def get_policy(policy_arn) response = @iam_client.get_policy(policy_arn: policy_arn) policy = response.policy @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.") policy rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.") raise rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}") raise end # Attaches a policy to a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def attach_policy_to_role(role_name, policy_arn) @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to role: #{e.message}") false end # Lists policy ARNs attached to a role # # @param role_name [String] The name of the role # @return [Array<String>] List of policy ARNs def list_attached_policy_arns(role_name) response = @iam_client.list_attached_role_policies(role_name: role_name) response.attached_policies.map(&:policy_arn) rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing policies attached to role: #{e.message}") [] end # Detaches a policy from a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def detach_policy_from_role(role_name, policy_arn) @iam_client.detach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from role: #{e.message}") false end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考ListPolicies中的。

以下代码示例演示了如何使用 ListRolePolicies

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Lists policy ARNs attached to a role # # @param role_name [String] The name of the role # @return [Array<String>] List of policy ARNs def list_attached_policy_arns(role_name) response = @iam_client.list_attached_role_policies(role_name: role_name) response.attached_policies.map(&:policy_arn) rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing policies attached to role: #{e.message}") [] end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考ListRolePolicies中的。

以下代码示例演示了如何使用 ListRoles

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Lists IAM roles up to a specified count. # @param count [Integer] the maximum number of roles to list. # @return [Array<String>] the names of the roles. def list_roles(count) role_names = [] roles_counted = 0 @iam_client.list_roles.each_page do |page| page.roles.each do |role| break if roles_counted >= count @logger.info("\t#{roles_counted + 1}: #{role.role_name}") role_names << role.role_name roles_counted += 1 end break if roles_counted >= count end role_names rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't list roles for the account. Here's why:") @logger.error("\t#{e.code}: #{e.message}") raise end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考ListRoles中的。

以下代码示例演示了如何使用 ListSAMLProviders

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。查找完整示例,了解如何在 Amazon 代码示例存储库中进行设置和运行。

class SamlProviderLister # Initializes the SamlProviderLister with IAM client and a logger. # @param iam_client [Aws::IAM::Client] The IAM client object. # @param logger [Logger] The logger object for logging output. def initialize(iam_client, logger = Logger.new($stdout)) @iam_client = iam_client @logger = logger end # Lists up to a specified number of SAML providers for the account. # @param count [Integer] The maximum number of providers to list. # @return [Aws::IAM::Client::Response] def list_saml_providers(count) response = @iam_client.list_saml_providers response.saml_provider_list.take(count).each do |provider| @logger.info("\t#{provider.arn}") end response rescue Aws::Errors::ServiceError => e @logger.error("Couldn't list SAML providers. Here's why:") @logger.error("\t#{e.code}: #{e.message}") raise end end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考中的 ListSAMLProviders

以下代码示例演示了如何使用 ListServerCertificates

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

列出、更新和删除服务器证书。

class ServerCertificateManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "ServerCertificateManager" end # Creates a new server certificate. # @param name [String] the name of the server certificate # @param certificate_body [String] the contents of the certificate # @param private_key [String] the private key contents # @return [Boolean] returns true if the certificate was successfully created def create_server_certificate(name, certificate_body, private_key) @iam_client.upload_server_certificate({ server_certificate_name: name, certificate_body: certificate_body, private_key: private_key, }) true rescue Aws::IAM::Errors::ServiceError => e puts "Failed to create server certificate: #{e.message}" false end # Lists available server certificate names. def list_server_certificate_names response = @iam_client.list_server_certificates if response.server_certificate_metadata_list.empty? @logger.info("No server certificates found.") return end response.server_certificate_metadata_list.each do |certificate_metadata| @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}") end rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing server certificates: #{e.message}") end # Updates the name of a server certificate. def update_server_certificate_name(current_name, new_name) @iam_client.update_server_certificate( server_certificate_name: current_name, new_server_certificate_name: new_name ) @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.") true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error updating server certificate name: #{e.message}") false end # Deletes a server certificate. def delete_server_certificate(name) @iam_client.delete_server_certificate(server_certificate_name: name) @logger.info("Server certificate '#{name}' deleted.") true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting server certificate: #{e.message}") false end end

以下代码示例演示了如何使用 ListUsers

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Lists all users in the AWS account # # @return [Array<Aws::IAM::Types::User>] An array of user objects def list_users users = [] @iam_client.list_users.each_page do |page| page.users.each do |user| users << user end end users rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing users: #{e.message}") [] end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考ListUsers中的。

以下代码示例演示了如何使用 PutUserPolicy

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Creates an inline policy for a specified user. # @param username [String] The name of the IAM user. # @param policy_name [String] The name of the policy to create. # @param policy_document [String] The JSON policy document. # @return [Boolean] def create_user_policy(username, policy_name, policy_document) @iam_client.put_user_policy({ user_name: username, policy_name: policy_name, policy_document: policy_document }) @logger.info("Policy #{policy_name} created for user #{username}.") true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't create policy #{policy_name} for user #{username}. Here's why:") @logger.error("\t#{e.code}: #{e.message}") false end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考PutUserPolicy中的。

以下代码示例演示了如何使用 UpdateServerCertificate

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

列出、更新和删除服务器证书。

class ServerCertificateManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "ServerCertificateManager" end # Creates a new server certificate. # @param name [String] the name of the server certificate # @param certificate_body [String] the contents of the certificate # @param private_key [String] the private key contents # @return [Boolean] returns true if the certificate was successfully created def create_server_certificate(name, certificate_body, private_key) @iam_client.upload_server_certificate({ server_certificate_name: name, certificate_body: certificate_body, private_key: private_key, }) true rescue Aws::IAM::Errors::ServiceError => e puts "Failed to create server certificate: #{e.message}" false end # Lists available server certificate names. def list_server_certificate_names response = @iam_client.list_server_certificates if response.server_certificate_metadata_list.empty? @logger.info("No server certificates found.") return end response.server_certificate_metadata_list.each do |certificate_metadata| @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}") end rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing server certificates: #{e.message}") end # Updates the name of a server certificate. def update_server_certificate_name(current_name, new_name) @iam_client.update_server_certificate( server_certificate_name: current_name, new_server_certificate_name: new_name ) @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.") true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error updating server certificate name: #{e.message}") false end # Deletes a server certificate. def delete_server_certificate(name) @iam_client.delete_server_certificate(server_certificate_name: name) @logger.info("Server certificate '#{name}' deleted.") true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting server certificate: #{e.message}") false end end

以下代码示例演示了如何使用 UpdateUser

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Updates an IAM user's name # # @param current_name [String] The current name of the user # @param new_name [String] The new name of the user def update_user_name(current_name, new_name) @iam_client.update_user(user_name: current_name, new_user_name: new_name) true rescue StandardError => e @logger.error("Error updating user name from '#{current_name}' to '#{new_name}': #{e.message}") false end
  • 有关 API 的详细信息,请参阅 Amazon SDK for Ruby API 参考UpdateUser中的。

场景

以下代码示例展示了如何创建用户并代入角色。

警告

为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证,而是使用与身份提供商的联合身份验证,例如 Amazon IAM Identity Center

  • 创建没有权限的用户。

  • 创建授予列出账户的 Amazon S3 存储桶的权限的角色

  • 添加策略以允许用户代入该角色。

  • 代入角色并使用临时凭证列出 S3 存储桶,然后清除资源。

适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

创建 IAM 用户和授予列出 Amazon S3 存储桶的权限的角色。用户仅具有代入该角色的权限。代入该角色后,使用临时凭证列出该账户的存储桶。

# Wraps the scenario actions. class ScenarioCreateUserAssumeRole attr_reader :iam_client # @param [Aws::IAM::Client] iam_client: The AWS IAM client. def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger end # Waits for the specified number of seconds. # # @param duration [Integer] The number of seconds to wait. def wait(duration) puts("Give AWS time to propagate resources...") sleep(duration) end # Creates a user. # # @param user_name [String] The name to give the user. # @return [Aws::IAM::User] The newly created user. def create_user(user_name) user = @iam_client.create_user(user_name: user_name).user @logger.info("Created demo user named #{user.user_name}.") rescue Aws::Errors::ServiceError => e @logger.info("Tried and failed to create demo user.") @logger.info("\t#{e.code}: #{e.message}") @logger.info("\nCan't continue the demo without a user!") raise else user end # Creates an access key for a user. # # @param user [Aws::IAM::User] The user that owns the key. # @return [Aws::IAM::AccessKeyPair] The newly created access key. def create_access_key_pair(user) user_key = @iam_client.create_access_key(user_name: user.user_name).access_key @logger.info("Created accesskey pair for user #{user.user_name}.") rescue Aws::Errors::ServiceError => e @logger.info("Couldn't create access keys for user #{user.user_name}.") @logger.info("\t#{e.code}: #{e.message}") raise else user_key end # Creates a role that can be assumed by a user. # # @param role_name [String] The name to give the role. # @param user [Aws::IAM::User] The user who is granted permission to assume the role. # @return [Aws::IAM::Role] The newly created role. def create_role(role_name, user) trust_policy = { Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: {'AWS': user.arn}, Action: "sts:AssumeRole" }] }.to_json role = @iam_client.create_role( role_name: role_name, assume_role_policy_document: trust_policy ).role @logger.info("Created role #{role.role_name}.") rescue Aws::Errors::ServiceError => e @logger.info("Couldn't create a role for the demo. Here's why: ") @logger.info("\t#{e.code}: #{e.message}") raise else role end # Creates a policy that grants permission to list S3 buckets in the account, and # then attaches the policy to a role. # # @param policy_name [String] The name to give the policy. # @param role [Aws::IAM::Role] The role that the policy is attached to. # @return [Aws::IAM::Policy] The newly created policy. def create_and_attach_role_policy(policy_name, role) policy_document = { Version: "2012-10-17", Statement: [{ Effect: "Allow", Action: "s3:ListAllMyBuckets", Resource: "arn:aws:s3:::*" }] }.to_json policy = @iam_client.create_policy( policy_name: policy_name, policy_document: policy_document ).policy @iam_client.attach_role_policy( role_name: role.role_name, policy_arn: policy.arn ) @logger.info("Created policy #{policy.policy_name} and attached it to role #{role.role_name}.") rescue Aws::Errors::ServiceError => e @logger.info("Couldn't create a policy and attach it to role #{role.role_name}. Here's why: ") @logger.info("\t#{e.code}: #{e.message}") raise end # Creates an inline policy for a user that lets the user assume a role. # # @param policy_name [String] The name to give the policy. # @param user [Aws::IAM::User] The user that owns the policy. # @param role [Aws::IAM::Role] The role that can be assumed. # @return [Aws::IAM::UserPolicy] The newly created policy. def create_user_policy(policy_name, user, role) policy_document = { Version: "2012-10-17", Statement: [{ Effect: "Allow", Action: "sts:AssumeRole", Resource: role.arn }] }.to_json @iam_client.put_user_policy( user_name: user.user_name, policy_name: policy_name, policy_document: policy_document ) puts("Created an inline policy for #{user.user_name} that lets the user assume role #{role.role_name}.") rescue Aws::Errors::ServiceError => e @logger.info("Couldn't create an inline policy for user #{user.user_name}. Here's why: ") @logger.info("\t#{e.code}: #{e.message}") raise end # Creates an Amazon S3 resource with specified credentials. This is separated into a # factory function so that it can be mocked for unit testing. # # @param credentials [Aws::Credentials] The credentials used by the Amazon S3 resource. def create_s3_resource(credentials) Aws::S3::Resource.new(client: Aws::S3::Client.new(credentials: credentials)) end # Lists the S3 buckets for the account, using the specified Amazon S3 resource. # Because the resource uses credentials with limited access, it may not be able to # list the S3 buckets. # # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource. def list_buckets(s3_resource) count = 10 s3_resource.buckets.each do |bucket| @logger.info "\t#{bucket.name}" count -= 1 break if count.zero? end rescue Aws::Errors::ServiceError => e if e.code == "AccessDenied" puts("Attempt to list buckets with no permissions: AccessDenied.") else @logger.info("Couldn't list buckets for the account. Here's why: ") @logger.info("\t#{e.code}: #{e.message}") raise end end # Creates an AWS Security Token Service (AWS STS) client with specified credentials. # This is separated into a factory function so that it can be mocked for unit testing. # # @param key_id [String] The ID of the access key used by the STS client. # @param key_secret [String] The secret part of the access key used by the STS client. def create_sts_client(key_id, key_secret) Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret) end # Gets temporary credentials that can be used to assume a role. # # @param role_arn [String] The ARN of the role that is assumed when these credentials # are used. # @param sts_client [AWS::STS::Client] An AWS STS client. # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role. def assume_role(role_arn, sts_client) credentials = Aws::AssumeRoleCredentials.new( client: sts_client, role_arn: role_arn, role_session_name: "create-use-assume-role-scenario" ) @logger.info("Assumed role '#{role_arn}', got temporary credentials.") credentials end # Deletes a role. If the role has policies attached, they are detached and # deleted before the role is deleted. # # @param role_name [String] The name of the role to delete. def delete_role(role_name) @iam_client.list_attached_role_policies(role_name: role_name).attached_policies.each do |policy| @iam_client.detach_role_policy(role_name: role_name, policy_arn: policy.policy_arn) @iam_client.delete_policy(policy_arn: policy.policy_arn) @logger.info("Detached and deleted policy #{policy.policy_name}.") end @iam_client.delete_role({ role_name: role_name }) @logger.info("Role deleted: #{role_name}.") rescue Aws::Errors::ServiceError => e @logger.info("Couldn't detach policies and delete role #{role.name}. Here's why:") @logger.info("\t#{e.code}: #{e.message}") raise end # Deletes a user. If the user has inline policies or access keys, they are deleted # before the user is deleted. # # @param user [Aws::IAM::User] The user to delete. def delete_user(user_name) user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata user.each do |key| @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name }) @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.") end @iam_client.delete_user(user_name: user_name) @logger.info("Deleted user '#{user_name}'.") rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error deleting user '#{user_name}': #{e.message}") end end # Runs the IAM create a user and assume a role scenario. def run_scenario(scenario) puts("-" * 88) puts("Welcome to the IAM create a user and assume a role demo!") puts("-" * 88) user = scenario.create_user("doc-example-user-#{Random.uuid}") user_key = scenario.create_access_key_pair(user) scenario.wait(10) role = scenario.create_role("doc-example-role-#{Random.uuid}", user) scenario.create_and_attach_role_policy("doc-example-role-policy-#{Random.uuid}", role) scenario.create_user_policy("doc-example-user-policy-#{Random.uuid}", user, role) scenario.wait(10) puts("Try to list buckets with credentials for a user who has no permissions.") puts("Expect AccessDenied from this call.") scenario.list_buckets( scenario.create_s3_resource(Aws::Credentials.new(user_key.access_key_id, user_key.secret_access_key))) puts("Now, assume the role that grants permission.") temp_credentials = scenario.assume_role( role.arn, scenario.create_sts_client(user_key.access_key_id, user_key.secret_access_key)) puts("Here are your buckets:") scenario.list_buckets(scenario.create_s3_resource(temp_credentials)) puts("Deleting role '#{role.role_name}' and attached policies.") scenario.delete_role(role.role_name) puts("Deleting user '#{user.user_name}', policies, and keys.") scenario.delete_user(user.user_name) puts("Thanks for watching!") puts("-" * 88) rescue Aws::Errors::ServiceError => e puts("Something went wrong with the demo.") puts("\t#{e.code}: #{e.message}") end run_scenario(ScenarioCreateUserAssumeRole.new(Aws::IAM::Client.new)) if $PROGRAM_NAME == __FILE__