CreateAccessKey 搭配 AWS SDK 或 CLI 使用 - AWS Identity and Access Management

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

CreateAccessKey 搭配 AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 CreateAccessKey

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Create an IAM access key for a user. /// </summary> /// <param name="userName">The username for which to create the IAM access /// key.</param> /// <returns>The AccessKey.</returns> public async Task<AccessKey> CreateAccessKeyAsync(string userName) { var response = await _IAMService.CreateAccessKeyAsync(new CreateAccessKeyRequest { UserName = userName, }); return response.AccessKey; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for .NET API Reference 中的 CreateAccessKey

Bash
AWS CLI 使用 Bash 指令碼
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_create_user_access_key # # This function creates an IAM access key for the specified user. # # Parameters: # -u user_name -- The name of the IAM user. # [-f file_name] -- The optional file name for the access key output. # # Returns: # [access_key_id access_key_secret] # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_create_user_access_key() { local user_name file_name response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_create_user_access_key" echo "Creates an AWS Identity and Access Management (IAM) key pair." echo " -u user_name The name of the IAM user." echo " [-f file_name] Optional file name for the access key output." echo "" } # Retrieve the calling parameters. while getopts "u:f:h" option; do case "${option}" in u) user_name="${OPTARG}" ;; f) file_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 response=$(aws iam create-access-key \ --user-name "$user_name" \ --output text) local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports create-access-key operation failed.$response" return 1 fi if [[ -n "$file_name" ]]; then echo "$response" >"$file_name" fi local key_id key_secret # shellcheck disable=SC2086 key_id=$(echo $response | cut -f 2 -d ' ') # shellcheck disable=SC2086 key_secret=$(echo $response | cut -f 4 -d ' ') echo "$key_id $key_secret" return 0 }
  • 如需 API 詳細資訊,請參閱《AWS CLI 命令參考》中的 CreateAccessKey

C++
SDK for C++
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 詳細資訊,請參閱 AWS SDK for C++ API Reference 中的 CreateAccessKey

CLI
AWS CLI

為 IAM 使用者建立存取金鑰

下列 create-access-key 命令會為名為 Bob 的 IAM 使用者建立存取金鑰 (存取金鑰 ID 與私密存取金鑰)。

aws iam create-access-key \ --user-name Bob

輸出:

{ "AccessKey": { "UserName": "Bob", "Status": "Active", "CreateDate": "2015-03-09T18:39:23.411Z", "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY", "AccessKeyId": "AKIAIOSFODNN7EXAMPLE" } }

請將私密存取金鑰存放在安全之處。遺失的金鑰無法復原,您必須建立新的存取金鑰。

如需詳細資訊,請參閱《AWS IAM 使用者指南》中的管理 IAM 使用者的存取金鑰

  • 如需 API 詳細資訊,請參閱《AWS CLI 命令參考》中的 CreateAccessKey

Go
SDK for Go V2
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import ( "context" "encoding/json" "errors" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/iam" "github.com/aws/aws-sdk-go-v2/service/iam/types" "github.com/aws/smithy-go" ) // 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 } // CreateAccessKeyPair creates an access key for a user. The returned access key contains // the ID and secret credentials needed to use the key. func (wrapper UserWrapper) CreateAccessKeyPair(ctx context.Context, userName string) (*types.AccessKey, error) { var key *types.AccessKey result, err := wrapper.IamClient.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{ UserName: aws.String(userName)}) if err != nil { log.Printf("Couldn't create access key pair for user %v. Here's why: %v\n", userName, err) } else { key = result.AccessKey } return key, err }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Go API Reference 中的 CreateAccessKey

Java
SDK for Java 2.x
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import software.amazon.awssdk.services.iam.model.CreateAccessKeyRequest; import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; 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 CreateAccessKey { public static void main(String[] args) { final String usage = """ Usage: <user>\s Where: user - An AWS IAM user that you can obtain from the AWS Management Console. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String user = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); String keyId = createIAMAccessKey(iam, user); System.out.println("The Key Id is " + keyId); iam.close(); } 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 詳細資訊,請參閱 AWS SDK for Java 2.x API Reference 中的 CreateAccessKey

JavaScript
SDK for JavaScript (v3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

建立存取金鑰。

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

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// 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 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 詳細資訊,請參閱 AWS SDK for Kotlin API reference 中的 CreateAccessKey

PowerShell
Tools for PowerShell

範例 1:此範例會建立新的存取金鑰和私密存取金鑰對,並將其指派給使用者 David。請確定將 AccessKeyIdSecretAccessKey 值儲存到檔案中,因為這是唯一可以取得 SecretAccessKey 的時機。您稍後便無法擷取它。若您遺失了密碼金鑰,必須建立新的存取金鑰對。

New-IAMAccessKey -UserName David

輸出:

AccessKeyId : AKIAIOSFODNN7EXAMPLE CreateDate : 4/13/2015 1:00:42 PM SecretAccessKey : wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY Status : Active UserName : David
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet Reference 中的 CreateAccessKey

Python
SDK for Python (Boto3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 詳細資訊,請參閱 AWS SDK for Python (Boto3) API Reference 中的 CreateAccessKey

Ruby
SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

此範例模組會列出、建立、停用和刪除存取金鑰。

# Manages access keys for IAM users class AccessKeyManager def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = 'AccessKeyManager' end # Lists access keys for a user # # @param user_name [String] The name of the user. def list_access_keys(user_name) response = @iam_client.list_access_keys(user_name: user_name) if response.access_key_metadata.empty? @logger.info("No access keys found for user '#{user_name}'.") else response.access_key_metadata.map(&:access_key_id) end rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Error listing access keys: cannot find user '#{user_name}'.") [] rescue StandardError => e @logger.error("Error listing access keys: #{e.message}") [] end # Creates an access key for a user # # @param user_name [String] The name of the user. # @return [Boolean] def create_access_key(user_name) response = @iam_client.create_access_key(user_name: user_name) access_key = response.access_key @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}") access_key rescue Aws::IAM::Errors::LimitExceeded @logger.error('Error creating access key: limit exceeded. Cannot create more.') nil rescue StandardError => e @logger.error("Error creating access key: #{e.message}") nil end # Deactivates an access key # # @param user_name [String] The name of the user. # @param access_key_id [String] The ID for the access key. # @return [Boolean] def deactivate_access_key(user_name, access_key_id) @iam_client.update_access_key( user_name: user_name, access_key_id: access_key_id, status: 'Inactive' ) true rescue StandardError => e @logger.error("Error deactivating access key: #{e.message}") false end # Deletes an access key # # @param user_name [String] The name of the user. # @param access_key_id [String] The ID for the access key. # @return [Boolean] def delete_access_key(user_name, access_key_id) @iam_client.delete_access_key( user_name: user_name, access_key_id: access_key_id ) true rescue StandardError => e @logger.error("Error deleting access key: #{e.message}") false end end
  • 如需 API 詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的 CreateAccessKey

Rust
SDK for Rust
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 詳細資訊,請參閱 AWS SDK for Rust API reference 中的 CreateAccessKey

Swift
SDK for Swift
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import AWSIAM import AWSS3 public func createAccessKey(userName: String) async throws -> IAMClientTypes.AccessKey { let input = CreateAccessKeyInput( userName: userName ) do { let output = try await iamClient.createAccessKey(input: input) guard let accessKey = output.accessKey else { throw ServiceHandlerError.keyError } return accessKey } catch { print("ERROR: createAccessKey:", dump(error)) throw error } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Swift API reference 中的 CreateAccessKey

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 將此服務與 AWS SDK 搭配使用。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。