使用 Amazon 开发工具包删除 IAM 访问密钥
以下代码示例显示如何删除 IAM 访问密钥。
- .NET
-
- Amazon SDK for .NET
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 /// <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 参考》中的 DeleteAccessKey。
-
- Go
-
- SDK for Go V2
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/iam" ) // IAMDeleteAccessKeyAPI defines the interface for the DeleteAccessKey function. // We use this interface to test the function using a mocked service. type IAMDeleteAccessKeyAPI interface { DeleteAccessKey(ctx context.Context, params *iam.DeleteAccessKeyInput, optFns ...func(*iam.Options)) (*iam.DeleteAccessKeyOutput, error) } // RemoveAccessKey deletes an AWS Identity and Access Management (IAM) access key. // Inputs: // c is the context of the method call, which includes the AWS Region. // api is the interface that defines the method call. // input defines the input arguments to the service call. // Output: // If successful, a DeleteAccessKeyOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to DeleteAccessKey. func RemoveAccessKey(c context.Context, api IAMDeleteAccessKeyAPI, input *iam.DeleteAccessKeyInput) (*iam.DeleteAccessKeyOutput, error) { return api.DeleteAccessKey(c, input) } func main() { keyID := flag.String("k", "", "The ID of the access key") userName := flag.String("u", "", "The name of the user") flag.Parse() if *keyID == "" || *userName == "" { fmt.Println("You must supply the key ID and user name (-k KEY-ID -u USER-NAME") return } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := iam.NewFromConfig(cfg) input := &iam.DeleteAccessKeyInput{ AccessKeyId: keyID, UserName: userName, } _, err = RemoveAccessKey(context.TODO(), client, input) if err != nil { fmt.Println("Error", err) return } fmt.Println("Deleted key with ID " + *keyID + " from user " + *userName) }-
有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 DeleteAccessKey
。
-
- Java
-
- SDK for Java 2.x
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 DeleteAccessKey。
-
- JavaScript
-
- SDK for JavaScript V3
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 创建客户端。
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 { DeleteAccessKeyCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { AccessKeyId: "ACCESS_KEY_ID", // ACCESS_KEY_ID UserName: "USER_NAME", // USER_NAME }; export const run = async () => { try { const data = await iamClient.send(new DeleteAccessKeyCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 DeleteAccessKey。
-
- SDK for JavaScript V2
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 // 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); } });-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 DeleteAccessKey。
-
- Kotlin
-
- SDK for Kotlin
-
注意 这是适用于预览版中功能的预发行文档。本文档随时可能更改。
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 DeleteAccessKey
。
-
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 DeleteAccessKey。
-
- Ruby
-
- SDK for Ruby
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 # 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 参考》中的 DeleteAccessKey。
-
- Rust
-
- SDK for Rust
-
注意 本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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.as_ref().unwrap()) .access_key_id(key.access_key_id.as_ref().unwrap()) .send() .await { Ok(_) => { break; } Err(e) => { println!("Can't delete the access key: {:?}", e); sleep(Duration::from_secs(2)).await; } } } Ok(()) }-
有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 DeleteAccessKey
。
-
有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。