使用 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> /// Create a new AccessKey for the user. /// </summary> /// <param name="client">The initialized IAM client object.</param> /// <param name="userName">The name of the user for whom to create the key.</param> /// <returns>A new IAM access key for the user.</returns> public static async Task<AccessKey> CreateAccessKeyAsync( AmazonIdentityManagementServiceClient client, string userName) { var request = new CreateAccessKeyRequest { UserName = userName, }; var response = await client.CreateAccessKeyAsync(request); if (response.AccessKey is not null) { Console.WriteLine($"Successfully created Access Key for {userName}."); } return response.AccessKey; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 CreateAccessKey

C++
SDK for C++
注意

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

Aws::String AwsDoc::IAM::createAccessKey(const Aws::String &userName, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::CreateAccessKeyRequest request; request.SetUserName(userName); Aws::String result; Aws::IAM::Model::CreateAccessKeyOutcome outcome = iam.CreateAccessKey(request); if (!outcome.IsSuccess()) { std::cerr << "Error creating access key for IAM user " << userName << ":" << outcome.GetError().GetMessage() << std::endl; } else { const auto &accessKey = outcome.GetResult().GetAccessKey(); std::cout << "Successfully created access key for IAM user " << userName << std::endl << " aws_access_key_id = " << accessKey.GetAccessKeyId() << std::endl << " aws_secret_access_key = " << accessKey.GetSecretAccessKey() << std::endl; result = accessKey.GetAccessKeyId(); } return result; }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 CreateAccessKey

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" ) // IMACreateAccessKeyAPI defines the interface for the CreateAccessKey function. // We use this interface to test the function using a mocked service. type IAMCreateAccessKeyAPI interface { CreateAccessKey(ctx context.Context, params *iam.CreateAccessKeyInput, optFns ...func(*iam.Options)) (*iam.CreateAccessKeyOutput, error) } // MakeAccessKey creates a new AWS Identity and Access Management (IAM) access key for a user. // 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 CreateAccessKeyOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to CreateAccessKey. func MakeAccessKey(c context.Context, api IAMCreateAccessKeyAPI, input *iam.CreateAccessKeyInput) (*iam.CreateAccessKeyOutput, error) { return api.CreateAccessKey(c, input) } func main() { userName := flag.String("u", "", "The name of the user") flag.Parse() if *userName == "" { fmt.Println("You must supply a user name (-u USER)") return } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := iam.NewFromConfig(cfg) input := &iam.CreateAccessKeyInput{ UserName: userName, } result, err := MakeAccessKey(context.TODO(), client, input) if err != nil { fmt.Println("Got an error creating a new access key") fmt.Println(err) return } fmt.Println("Created new access key with ID: " + *result.AccessKey.AccessKeyId + " and secret key: " + *result.AccessKey.SecretAccessKey) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 CreateAccessKey

Java
SDK for Java 2.x
注意

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

public static String createIAMAccessKey(IamClient iam,String user) { try { CreateAccessKeyRequest request = CreateAccessKeyRequest.builder() .userName(user) .build(); CreateAccessKeyResponse response = iam.createAccessKey(request); return response.accessKey().accessKeyId(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 CreateAccessKey

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 { CreateAccessKeyCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = {UserName: "IAM_USER_NAME"}; //IAM_USER_NAME export const run = async () => { try { const data = await iamClient.send(new CreateAccessKeyCommand(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'}); iam.createAccessKey({UserName: 'IAM_USER_NAME'}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.AccessKey); } });
Kotlin
SDK for Kotlin
注意

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

注意

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

suspend fun createIAMAccessKey(user: String?): String { val request = CreateAccessKeyRequest { userName = user } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createAccessKey(request) return response.accessKey?.accessKeyId.toString() } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 CreateAccessKey

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

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

def create_key(user_name): """ Creates an access key for the specified user. Each user can have a maximum of two keys. :param user_name: The name of the user. :return: The created access key. """ try: key_pair = iam.User(user_name).create_access_key_pair() logger.info( "Created access key pair for %s. Key ID is %s.", key_pair.user_name, key_pair.id) except ClientError: logger.exception("Couldn't create access key pair for %s.", user_name) raise else: return key_pair
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的CreateAccessKey

Ruby
SDK for Ruby
注意

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

# Creates an access key for a user. # # @param user [Aws::IAM::User] The user that owns the key. # @return [Aws::IAM::AccessKeyPair] The newly created access key. def create_access_key_pair(user) user_key = user.create_access_key_pair puts("Created access key pair for user.") rescue Aws::Errors::ServiceError => e puts("Couldn't create access keys for user #{user.name}.") puts("\t#{e.code}: #{e.message}") raise else user_key end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 CreateAccessKey

Rust
SDK for Rust
注意

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

注意

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

pub async fn create_access_key(client: &iamClient, user_name: &str) -> Result<AccessKey, iamError> { let mut tries: i32 = 0; let max_tries: i32 = 10; let response: Result<CreateAccessKeyOutput, SdkError<CreateAccessKeyError>> = loop { match client.create_access_key().user_name(user_name).send().await { Ok(inner_response) => { break Ok(inner_response); } Err(e) => { tries += 1; if tries > max_tries { break Err(e); } sleep(Duration::from_secs(2)).await; } } }; Ok(response.unwrap().access_key.unwrap()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 CreateAccessKey

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