DeleteAccessKey 搭配 AWS SDK或 使用 CLI - AWS Identity and Access Management

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

DeleteAccessKey 搭配 AWS SDK或 使用 CLI

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

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

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

/// <summary> /// Delete an IAM user's access key. /// </summary> /// <param name="accessKeyId">The Id for the IAM access key.</param> /// <param name="userName">The username of the user that owns the IAM /// access key.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteAccessKeyAsync(string accessKeyId, string userName) { var response = await _IAMService.DeleteAccessKeyAsync(new DeleteAccessKeyRequest { AccessKeyId = accessKeyId, UserName = userName, }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • 如需API詳細資訊,請參閱 參考 DeleteAccessKey中的 。 AWS SDK for .NET API

Bash
AWS CLI 使用 Bash 指令碼
注意

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

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_delete_access_key # # This function deletes an IAM access key for the specified IAM user. # # Parameters: # -u user_name -- The name of the user. # -k access_key -- The access key to delete. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_delete_access_key() { local user_name access_key response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_delete_access_key" echo "Deletes an WS Identity and Access Management (IAM) access key for the specified IAM user" echo " -u user_name The name of the user." echo " -k access_key The access key to delete." echo "" } # Retrieve the calling parameters. while getopts "u:k:h" option; do case "${option}" in u) user_name="${OPTARG}" ;; k) access_key="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$user_name" ]]; then errecho "ERROR: You must provide a username with the -u parameter." usage return 1 fi if [[ -z "$access_key" ]]; then errecho "ERROR: You must provide an access key with the -k parameter." usage return 1 fi iecho "Parameters:\n" iecho " Username: $user_name" iecho " Access key: $access_key" iecho "" response=$(aws iam delete-access-key \ --user-name "$user_name" \ --access-key-id "$access_key") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-access-key operation failed.\n$response" return 1 fi iecho "delete-access-key response:$response" iecho return 0 }
  • 如需API詳細資訊,請參閱 命令參考 DeleteAccessKey中的 。 AWS CLI

C++
SDK 適用於 C++
注意

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

bool AwsDoc::IAM::deleteAccessKey(const Aws::String &userName, const Aws::String &accessKeyID, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::DeleteAccessKeyRequest request; request.SetUserName(userName); request.SetAccessKeyId(accessKeyID); auto outcome = iam.DeleteAccessKey(request); if (!outcome.IsSuccess()) { std::cerr << "Error deleting access key " << accessKeyID << " from user " << userName << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted access key " << accessKeyID << " for IAM user " << userName << std::endl; } return outcome.IsSuccess(); }
  • 如需API詳細資訊,請參閱 參考 DeleteAccessKey中的 。 AWS SDK for C++ API

CLI
AWS CLI

刪除IAM使用者的存取金鑰

下列delete-access-key命令會刪除名為 之IAM使用者的指定存取金鑰 (存取金鑰 ID 和秘密存取金鑰)Bob

aws iam delete-access-key \ --access-key-id AKIDPMS9RO4H3FEXAMPLE \ --user-name Bob

此命令不會產生輸出。

若要列出為IAM使用者定義的存取金鑰,請使用 list-access-keys命令。

如需詳細資訊,請參閱 AWS IAM 使用者指南 中的管理IAM使用者的存取金鑰

  • 如需API詳細資訊,請參閱 命令參考 DeleteAccessKey中的 。 AWS CLI

Go
SDK for Go V2
注意

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

// UserWrapper encapsulates user actions used in the examples. // It contains an IAM service client that is used to perform user actions. type UserWrapper struct { IamClient *iam.Client } // DeleteAccessKey deletes an access key from a user. func (wrapper UserWrapper) DeleteAccessKey(ctx context.Context, userName string, keyId string) error { _, err := wrapper.IamClient.DeleteAccessKey(ctx, &iam.DeleteAccessKeyInput{ AccessKeyId: aws.String(keyId), UserName: aws.String(userName), }) if err != nil { log.Printf("Couldn't delete access key %v. Here's why: %v\n", keyId, err) } return err }
  • 如需API詳細資訊,請參閱 參考 DeleteAccessKey中的 。 AWS SDK for Go API

Java
SDK 適用於 Java 2.x
注意

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

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest; import software.amazon.awssdk.services.iam.model.IamException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteAccessKey { public static void main(String[] args) { final String usage = """ Usage: <username> <accessKey>\s Where: username - The name of the user.\s accessKey - The access key ID for the secret access key you want to delete.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String username = args[0]; String accessKey = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); deleteKey(iam, username, accessKey); iam.close(); } public static void deleteKey(IamClient iam, String username, String accessKey) { try { DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder() .accessKeyId(accessKey) .userName(username) .build(); iam.deleteAccessKey(request); System.out.println("Successfully deleted access key " + accessKey + " from user " + username); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 如需API詳細資訊,請參閱 參考 DeleteAccessKey中的 。 AWS SDK for Java 2.x API

JavaScript
SDK 適用於 JavaScript (v3)
注意

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

刪除存取金鑰。

import { DeleteAccessKeyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} userName * @param {string} accessKeyId */ export const deleteAccessKey = (userName, accessKeyId) => { const command = new DeleteAccessKeyCommand({ AccessKeyId: accessKeyId, UserName: userName, }); return client.send(command); };
SDK 適用於 JavaScript (v2)
注意

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

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { AccessKeyId: "ACCESS_KEY_ID", UserName: "USER_NAME", }; iam.deleteAccessKey(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
Kotlin
SDK 適用於 Kotlin
注意

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

suspend fun deleteKey( userNameVal: String, accessKey: String, ) { val request = DeleteAccessKeyRequest { accessKeyId = accessKey userName = userNameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deleteAccessKey(request) println("Successfully deleted access key $accessKey from $userNameVal") } }
  • 如需API詳細資訊,請參閱DeleteAccessKey中的 AWS SDK for Kotlin API參考

PowerShell
適用於 的工具 PowerShell

範例 1:此範例AKIAIOSFODNN7EXAMPLE會從名為 的使用者中刪除具有金鑰 ID 的 AWS 存取金鑰對Bob

Remove-IAMAccessKey -AccessKeyId AKIAIOSFODNN7EXAMPLE -UserName Bob -Force
  • 如需API詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考 DeleteAccessKey中的 。

Python
SDK for Python (Boto3)
注意

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

def delete_key(user_name, key_id): """ Deletes a user's access key. :param user_name: The user that owns the key. :param key_id: The ID of the key to delete. """ try: key = iam.AccessKey(user_name, key_id) key.delete() logger.info("Deleted access key %s for %s.", key.id, key.user_name) except ClientError: logger.exception("Couldn't delete key %s for %s", key_id, user_name) raise
  • 如需API詳細資訊,請參閱 DeleteAccessKey 中的 AWS SDK for Python (Boto3) API參考

Ruby
SDK 適用於 Ruby
注意

還有更多 。 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 @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 @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詳細資訊,請參閱 參考 DeleteAccessKey中的 。 AWS SDK for Ruby API

Rust
SDK for Rust
注意

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

pub async fn delete_access_key( client: &iamClient, user: &User, key: &AccessKey, ) -> Result<(), iamError> { loop { match client .delete_access_key() .user_name(user.user_name()) .access_key_id(key.access_key_id()) .send() .await { Ok(_) => { break; } Err(e) => { println!("Can't delete the access key: {:?}", e); sleep(Duration::from_secs(2)).await; } } } Ok(()) }
  • 如需API詳細資訊,請參閱 DeleteAccessKey 中的 AWS SDK for Rust API參考

Swift
SDK 適用於 Swift
注意

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

import AWSIAM import AWSS3 public func deleteAccessKey(user: IAMClientTypes.User? = nil, key: IAMClientTypes.AccessKey) async throws { let userName: String? if user != nil { userName = user!.userName } else { userName = nil } let input = DeleteAccessKeyInput( accessKeyId: key.accessKeyId, userName: userName ) do { _ = try await iamClient.deleteAccessKey(input: input) } catch { print("ERROR: deleteAccessKey:", dump(error)) throw error } }
  • 如需API詳細資訊,請參閱 DeleteAccessKey 中的 AWS SDK Swift API參考

如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱 將此服務與 搭配使用 AWS SDK。本主題也包含有關入門的資訊,以及先前SDK版本的詳細資訊。