使用 Amazon 开发工具包删除 IAM 用户 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包删除 IAM 用户

以下代码示例显示如何删除 IAM 用户。

.NET
Amazon SDK for .NET
注意

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

/// <summary> /// Delete the user, and other resources created for this example. /// </summary> /// <param name="client">The initialized client object.</param> /// <param name=accessKeyId">The Id of the user's access key.</param>" /// <param name="userName">The user name of the user to delete.</param> /// <param name="policyName">The name of the policy to delete.</param> /// <param name="policyArn">The Amazon Resource Name ARN of the Policy to delete.</param> /// <param name="roleName">The name of the role that will be deleted.</param> public static async Task DeleteResourcesAsync( AmazonIdentityManagementServiceClient client, string accessKeyId, string userName, string policyArn, string roleName) { var detachPolicyResponse = await client.DetachRolePolicyAsync(new DetachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName, }); var delPolicyResponse = await client.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn, }); var delRoleResponse = await client.DeleteRoleAsync(new DeleteRoleRequest { RoleName = roleName, }); var delAccessKey = await client.DeleteAccessKeyAsync(new DeleteAccessKeyRequest { AccessKeyId = accessKeyId, UserName = userName, }); var delUserResponse = await client.DeleteUserAsync(new DeleteUserRequest { UserName = userName, }); }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 DeleteUser

C++
SDK for C++
注意

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

Go
SDK for Go V2
注意

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

// DeleteUser _, err = service.DeleteUser(context.Background(), &iam.DeleteUserInput{ UserName: aws.String(ExampleUserName), }) if err != nil { panic("Couldn't delete user: " + err.Error()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 DeleteUser

Java
SDK for Java 2.x
注意

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

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 { IAMClient } from "@aws-sdk/client-iam"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". // Create an IAM service client object. const iamClient = new IAMClient({ region: REGION }); export { iamClient };

请删除用户。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { DeleteUserCommand, GetUserCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { UserName: "USER_NAME" }; //USER_NAME export const run = async () => { try { const data = await iamClient.send(new GetUserCommand(params)); return data; try { const results = await iamClient.send(new DeleteUserCommand(params)); console.log("Success", results); return results; } catch (err) { console.log("Error", err); } } catch (err) { console.log("User " + "USER_NAME" + " does not exist."); } }; run();
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
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

注意

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

Python
适用于 Python (Boto3) 的 SDK
注意

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
SDK for Ruby
注意

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

# 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) user.policies.each do |policy| name = policy.name policy.delete puts("Deleted user policy #{name}.") end user.access_keys.each do |key| key.delete puts("Deleted access key for user #{user.name}.") end name = user.name user.delete puts("Deleted user #{name}.") rescue Aws::Errors::ServiceError => e puts("Couldn't detach policies and delete user #{user.name}. Here's why:") puts("\t#{e.code}: #{e.message}") end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 DeleteUser

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

注意

在 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.as_ref().unwrap()) .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

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