IAM使用紅寶石SDK的例子 - AWS SDK 程式碼範例

AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

IAM使用紅寶石SDK的例子

下列程式碼範例說明如何使用 AWS SDK for Ruby 與來執行動作及實作常見案例IAM。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會顯示如何呼叫個別服務函數,但您可以在其相關案例中查看內容中的動作。

例是程式碼範例,向您展示如何透過呼叫服務中的多個函數或與其他函式結合來完成特定工作 AWS 服務。

每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。

開始使用

下列程式碼範例會示範如何開始使用IAM。

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

require 'aws-sdk-iam' require 'logger' # IAMManager is a class responsible for managing IAM operations # such as listing all IAM policies in the current AWS account. class IAMManager def initialize(client) @client = client @logger = Logger.new($stdout) end # Lists and prints all IAM policies in the current AWS account. def list_policies @logger.info('Here are the IAM policies in your account:') paginator = @client.list_policies policies = [] paginator.each_page do |page| policies.concat(page.policies) end if policies.empty? @logger.info("You don't have any IAM policies.") else policies.each do |policy| @logger.info("- #{policy.policy_name}") end end end end if $PROGRAM_NAME == __FILE__ iam_client = Aws::IAM::Client.new manager = IAMManager.new(iam_client) manager.list_policies end
  • 如需詳API細資訊,請參閱AWS SDK for Ruby API參考ListPolicies中的。

動作

下列程式碼範例會示範如何使用AttachRolePolicy

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、附加和解除連結角色原則。

# 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細資訊,請參閱AWS SDK for Ruby API參考AttachRolePolicy中的。

下列程式碼範例會示範如何使用AttachUserPolicy

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考AttachUserPolicy中的。

下列程式碼範例會示範如何使用CreateAccessKey

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、停用及刪除存取金鑰。

# 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細資訊,請參閱AWS SDK for Ruby API參考CreateAccessKey中的。

下列程式碼範例會示範如何使用CreateAccountAlias

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

列出、建立及刪除帳戶別名。

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

下列程式碼範例會示範如何使用CreatePolicy

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、附加和解除連結角色原則。

# 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細資訊,請參閱AWS SDK for Ruby API參考CreatePolicy中的。

下列程式碼範例會示範如何使用CreateRole

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考CreateRole中的。

下列程式碼範例會示範如何使用CreateServiceLinkedRole

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考CreateUser中的。

下列程式碼範例會示範如何使用DeleteAccessKey

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、停用及刪除存取金鑰。

# 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細資訊,請參閱AWS SDK for Ruby API參考DeleteAccessKey中的。

下列程式碼範例會示範如何使用DeleteAccountAlias

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

列出、建立及刪除帳戶別名。

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

下列程式碼範例會示範如何使用DeleteRole

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考DeleteRole中的。

下列程式碼範例會示範如何使用DeleteServerCertificate

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

列出、更新和刪除伺服器憑證。

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

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考DeleteUser中的。

下列程式碼範例會示範如何使用DeleteUserPolicy

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考DeleteUserPolicy中的。

下列程式碼範例會示範如何使用DetachRolePolicy

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、附加和解除連結角色原則。

# 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細資訊,請參閱AWS SDK for Ruby API參考DetachRolePolicy中的。

下列程式碼範例會示範如何使用DetachUserPolicy

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考DetachUserPolicy中的。

下列程式碼範例會示範如何使用GetAccountPasswordPolicy

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考GetPolicy中的。

下列程式碼範例會示範如何使用GetRole

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考GetRole中的。

下列程式碼範例會示範如何使用GetUser

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考GetUser中的。

下列程式碼範例會示範如何使用ListAccessKeys

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、停用及刪除存取金鑰。

# 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細資訊,請參閱AWS SDK for Ruby API參考ListAccessKeys中的。

下列程式碼範例會示範如何使用ListAccountAliases

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

列出、建立及刪除帳戶別名。

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

下列程式碼範例會示範如何使用ListAttachedRolePolicies

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、附加和解除連結角色原則。

# 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

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考ListGroups中的。

下列程式碼範例會示範如何使用ListPolicies

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、附加和解除連結角色原則。

# 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細資訊,請參閱AWS SDK for Ruby API參考ListPolicies中的。

下列程式碼範例會示範如何使用ListRolePolicies

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考ListRolePolicies中的。

下列程式碼範例會示範如何使用ListRoles

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考ListRoles中的。

下列程式碼範例會示範如何使用ListSAMLProviders

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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細資訊,請參閱AWS SDK for Ruby API參考資料istSAMLProviders中的 L

下列程式碼範例會示範如何使用ListServerCertificates

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

列出、更新和刪除伺服器憑證。

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

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考ListUsers中的。

下列程式碼範例會示範如何使用PutUserPolicy

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考PutUserPolicy中的。

下列程式碼範例會示範如何使用UpdateServerCertificate

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

列出、更新和刪除伺服器憑證。

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

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# 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細資訊,請參閱AWS SDK for Ruby API參考UpdateUser中的。

案例

下列程式碼範例示範如何建立使用者並擔任角色。

警告

為避免安全風險,在開發專用軟件或使IAM用真實數據時,請勿使用用戶進行身份驗證。相反地,搭配使用聯合功能和身分提供者,例如 AWS IAM Identity Center

  • 建立沒有許可的使用者。

  • 建立一個可授予許可的角色,以列出帳戶的 Amazon S3 儲存貯體。

  • 新增政策,讓使用者擔任該角色。

  • 使用暫時憑證,擔任角色並列出 Amazon S3 儲存貯體,然後清理資源。

SDK對於紅寶石
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

建立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__