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

使用 Amazon 开发工具包更新 IAM 访问密钥

以下代码示例演示了如何更新 IAM 访问密钥。

C++
SDK for C++
注意

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

bool AwsDoc::IAM::updateAccessKey(const Aws::String &userName, const Aws::String &accessKeyID, Aws::IAM::Model::StatusType status, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::UpdateAccessKeyRequest request; request.SetUserName(userName); request.SetAccessKeyId(accessKeyID); request.SetStatus(status); auto outcome = iam.UpdateAccessKey(request); if (outcome.IsSuccess()) { std::cout << "Successfully updated status of access key " << accessKeyID << " for user " << userName << std::endl; } else { std::cerr << "Error updated status of access key " << accessKeyID << " for user " << userName << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 UpdateAccessKey

Go
SDK for Go V2
注意

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

package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/iam" "github.com/aws/aws-sdk-go-v2/service/iam/types" ) // IAMUpdateAccessKeyAPI defines the interface for the UpdateAccessKey function. // We use this interface to test the function using a mocked service. type IAMUpdateAccessKeyAPI interface { UpdateAccessKey(ctx context.Context, params *iam.UpdateAccessKeyInput, optFns ...func(*iam.Options)) (*iam.UpdateAccessKeyOutput, error) } // ActivateKey sets the status of an AWS Identity and Access Management (IAM) access key to active. // 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 UpdateAccessKeyOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to UpdateAccessKey. func ActivateKey(c context.Context, api IAMUpdateAccessKeyAPI, input *iam.UpdateAccessKeyInput) (*iam.UpdateAccessKeyOutput, error) { return api.UpdateAccessKey(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 an access 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.UpdateAccessKeyInput{ AccessKeyId: keyID, Status: types.StatusTypeActive, UserName: userName, } _, err = ActivateKey(context.TODO(), client, input) if err != nil { fmt.Println("Error", err) return } fmt.Println("Access Key activated") }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 UpdateAccessKey

Java
SDK for Java 2.x
注意

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

public static void updateKey(IamClient iam, String username, String accessId, String status ) { try { if (status.toLowerCase().equalsIgnoreCase("active")) { statusType = StatusType.ACTIVE; } else if (status.toLowerCase().equalsIgnoreCase("inactive")) { statusType = StatusType.INACTIVE; } else { statusType = StatusType.UNKNOWN_TO_SDK_VERSION; } UpdateAccessKeyRequest request = UpdateAccessKeyRequest.builder() .accessKeyId(accessId) .userName(username) .status(statusType) .build(); iam.updateAccessKey(request); System.out.printf("Successfully updated the status of access key %s to" + "status %s for user %s", accessId, status, username); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 UpdateAccessKey

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 { UpdateAccessKeyCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { AccessKeyId: "ACCESS_KEY_ID", //ACCESS_KEY_ID Status: "Active", UserName: "USER_NAME", //USER_NAME }; export const run = async () => { try { const data = await iamClient.send(new UpdateAccessKeyCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; 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 = { AccessKeyId: 'ACCESS_KEY_ID', Status: 'Active', UserName: 'USER_NAME' }; iam.updateAccessKey(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
Python
适用于 Python (Boto3) 的 SDK
注意

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

def update_key(user_name, key_id, activate): """ Updates the status of a key. :param user_name: The user that owns the key. :param key_id: The ID of the key to update. :param activate: When True, the key is activated. Otherwise, the key is deactivated. """ try: key = iam.User(user_name).AccessKey(key_id) if activate: key.activate() else: key.deactivate() logger.info("%s key %s.", 'Activated' if activate else 'Deactivated', key_id) except ClientError: logger.exception( "Couldn't %s key %s.", 'Activate' if activate else 'Deactivate', key_id) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 UpdateAccessKey

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