将 DeleteUser 与 Amazon SDK 或 CLI 配合使用 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

DeleteUser 与 Amazon SDK 或 CLI 配合使用

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

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,了解如何在 Amazon 代码示例存储库中进行设置和运行。

/// <summary> /// Delete an IAM user. /// </summary> /// <param name="userName">The username of the IAM user to delete.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteUserAsync(string userName) { var response = await _IAMService.DeleteUserAsync(new DeleteUserRequest { UserName = userName }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 DeleteUser

Bash
Amazon CLI 及 Bash 脚本
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_delete_user # # This function deletes the specified IAM user. # # Parameters: # -u user_name -- The name of the user to create. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_delete_user() { local user_name response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_delete_user" echo "Deletes an WS Identity and Access Management (IAM) user. You must supply a username:" echo " -u user_name The name of the user." echo "" } # Retrieve the calling parameters. while getopts "u:h" option; do case "${option}" in u) user_name="${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 iecho "Parameters:\n" iecho " User name: $user_name" iecho "" # If the user does not exist, we don't want to try to delete it. if (! iam_user_exists "$user_name"); then errecho "ERROR: A user with that name does not exist in the account." return 1 fi response=$(aws iam delete-user \ --user-name "$user_name") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-user operation failed.$response" return 1 fi iecho "delete-user response:$response" iecho return 0 }
  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 DeleteUser

C++
适用于 C++ 的 SDK
注意

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

Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::DeleteUserRequest request; request.SetUserName(userName); auto outcome = iam.DeleteUser(request); if (!outcome.IsSuccess()) { std::cerr << "Error deleting IAM user " << userName << ": " << outcome.GetError().GetMessage() << std::endl;; } else { std::cout << "Successfully deleted IAM user " << userName << std::endl; } return outcome.IsSuccess();
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 DeleteUser

CLI
Amazon CLI

要删除 IAM 用户

以下 delete-user 命令可将名为 Bob 的 IAM 用户从当前账户中删除。

aws iam delete-user \ --user-name Bob

此命令不生成任何输出。

有关更多信息,请参阅《Amazon IAM 用户指南》中的删除 IAM 用户

  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 DeleteUser

Go
适用于 Go V2 的 SDK
注意

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

// 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 } // DeleteUser deletes a user. func (wrapper UserWrapper) DeleteUser(userName string) error { _, err := wrapper.IamClient.DeleteUser(context.TODO(), &iam.DeleteUserInput{ UserName: aws.String(userName), }) if err != nil { log.Printf("Couldn't delete user %v. Here's why: %v\n", userName, err) } return err }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 DeleteUser

Java
SDK for Java 2.x
注意

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

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.model.DeleteUserRequest; 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 DeleteUser { public static void main(String[] args) { final String usage = """ Usage: <userName>\s Where: userName - The name of the user to delete.\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String userName = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); deleteIAMUser(iam, userName); System.out.println("Done"); iam.close(); } public static void deleteIAMUser(IamClient iam, String userName) { try { DeleteUserRequest request = DeleteUserRequest.builder() .userName(userName) .build(); iam.deleteUser(request); System.out.println("Successfully deleted IAM user " + userName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 DeleteUser

JavaScript
SDK for JavaScript (v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

删除用户。

import { DeleteUserCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} name */ export const deleteUser = (name) => { const command = new DeleteUserCommand({ UserName: name }); return client.send(command); };
SDK for JavaScript (v2)
注意

在 GitHub 上查看更多内容。查找完整示例,了解如何在 Amazon 代码示例存储库中进行设置和运行。

// 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 = { UserName: process.argv[2], }; iam.getUser(params, function (err, data) { if (err && err.code === "NoSuchEntity") { console.log("User " + process.argv[2] + " does not exist."); } else { iam.deleteUser(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); } });
Kotlin
适用于 Kotlin 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun deleteIAMUser(userNameVal: String) { val request = DeleteUserRequest { userName = userNameVal } // To delete a user, ensure that the user's access keys are deleted first. IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deleteUser(request) println("Successfully deleted user $userNameVal") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 DeleteUser

PowerShell
适用于 PowerShell 的工具

示例 1:此示例删除名为 Bob 的 IAM 用户。

Remove-IAMUser -UserName Bob

示例 2:此示例删除名为 Theresa 的 IAM 用户,以及必须先删除的所有元素。

$name = "Theresa" # find any groups and remove user from them $groups = Get-IAMGroupForUser -UserName $name foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName $name -Force } # find any inline policies and delete them $inlinepols = Get-IAMUserPolicies -UserName $name foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName $name -Force} # find any managed polices and detach them $managedpols = Get-IAMAttachedUserPolicies -UserName $name foreach ($pol in $managedpols) { Unregister-IAMUserPolicy -PolicyArn $pol.PolicyArn -UserName $name } # find any signing certificates and delete them $certs = Get-IAMSigningCertificate -UserName $name foreach ($cert in $certs) { Remove-IAMSigningCertificate -CertificateId $cert.CertificateId -UserName $name -Force } # find any access keys and delete them $keys = Get-IAMAccessKey -UserName $name foreach ($key in $keys) { Remove-IAMAccessKey -AccessKeyId $key.AccessKeyId -UserName $name -Force } # delete the user's login profile, if one exists - note: need to use try/catch to suppress not found error try { $prof = Get-IAMLoginProfile -UserName $name -ea 0 } catch { out-null } if ($prof) { Remove-IAMLoginProfile -UserName $name -Force } # find any MFA device, detach it, and if virtual, delete it. $mfa = Get-IAMMFADevice -UserName $name if ($mfa) { Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber } } # finally, remove the user Remove-IAMUser -UserName $name -Force
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 DeleteUser

Python
SDK for Python(Boto3)
注意

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

def delete_user(user_name): """ Deletes a user. Before a user can be deleted, all associated resources, such as access keys and policies, must be deleted or detached. :param user_name: The name of the user. """ try: iam.User(user_name).delete() logger.info("Deleted user %s.", user_name) except ClientError: logger.exception("Couldn't delete user %s.", user_name) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 DeleteUser

Ruby
适用于 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

Rust
适用于 Rust 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

pub async fn delete_user(client: &iamClient, user: &User) -> Result<(), SdkError<DeleteUserError>> { let user = user.clone(); let mut tries: i32 = 0; let max_tries: i32 = 10; let response: Result<(), SdkError<DeleteUserError>> = loop { match client .delete_user() .user_name(user.user_name()) .send() .await { Ok(_) => { break Ok(()); } Err(e) => { tries += 1; if tries > max_tries { break Err(e); } sleep(Duration::from_secs(2)).await; } } }; response }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 DeleteUser

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

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

public func deleteUser(user: IAMClientTypes.User) async throws { let input = DeleteUserInput( userName: user.userName ) do { _ = try await iamClient.deleteUser(input: input) } catch { throw error } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Swift API 参考》中的 DeleteUser

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。