

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon Bedrock API 키 생성
<a name="api-keys-generate"></a>

 AWS Management Console 또는 API를 사용하여 Amazon Bedrock AWS API 키를 생성할 수 있습니다. AWS Management Console 를 사용하여 몇 단계만으로 Amazon Bedrock API 키를 쉽게 생성하는 것이 좋습니다.

**주의**  
Amazon Bedrock 탐색을 위해 Amazon Bedrock API 키 사용을 제한하는 것이 좋습니다. 보안 요구 사항이 더 큰 애플리케이션에 Amazon Bedrock을 통합할 준비가 되면 단기 자격 증명으로 전환해야 합니다. 자세한 내용은 IAM 사용 설명서의 [장기 액세스 키의 대안](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)을 참조하세요.

**Topics**
+ [콘솔을 사용하여 Amazon Bedrock API 키 생성](#api-keys-generate-console)
+ [API를 사용하여 장기 Amazon Bedrock API 키 생성](#api-keys-generate-api-long-term)
+ [클라이언트 라이브러리를 사용하여 단기 Amazon Bedrock API 키 생성](#api-keys-generate-short-term)
+ [단기 Amazon Bedrock API 키의 자동 새로 고침 설정](#api-keys-refresh-short-term)

## 콘솔을 사용하여 Amazon Bedrock API 키 생성
<a name="api-keys-generate-console"></a>

콘솔을 사용하여 Amazon Bedrock API 키를 생성하려면 다음을 수행합니다.

1. Amazon Bedrock 콘솔을 사용할 권한이 있는 IAM 자격 증명 AWS Management Console 으로에 로그인합니다. 그 다음 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock)에서 Amazon Bedrock 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **API 키**를 선택합니다.

1. 다음 유형의 키 중 하나를 생성합니다.
   + **단기 API 키** - **단기 API 키** 탭에서 **단기 API 키 생성**을 선택합니다. 키는 콘솔 세션이 만료되면 만료되고(12시간 이내) 키를 생성한에 호출 AWS 리전 할 수 있습니다. 생성된 키에서 직접 리전을 수정할 수 있습니다.
   + **장기 API 키** - **장기 API 키** 탭에서 **장기 API 키 생성**을 선택합니다.

     1. **API 키 만료** 섹션에서 키가 만료될 시간을 선택합니다.

     1. (선택 사항) 기본적으로 핵심 Amazon Bedrock API 작업에 대한 액세스 권한을 부여하는 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) AWS관리형 정책은 키와 연결된 IAM 사용자에게 연결됩니다. 사용자에게 연결할 정책을 더 선택하려면 **고급 권한** 섹션을 확장하고 추가하려는 정책을 선택합니다.

     1. **생성**을 선택합니다.
**주의**  
Amazon Bedrock 탐색을 위해 Amazon Bedrock API 키 사용을 제한하는 것이 좋습니다. 보안 요구 사항이 더 큰 애플리케이션에 Amazon Bedrock을 통합할 준비가 되면 단기 자격 증명으로 전환해야 합니다. 자세한 내용은 IAM 사용 설명서의 [장기 액세스 키의 대안](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)을 참조하세요.



## API를 사용하여 장기 Amazon Bedrock API 키 생성
<a name="api-keys-generate-api-long-term"></a>

API에서 장기 Amazon Bedrock API 키를 생성하는 일반적인 단계는 다음과 같습니다.

1. [IAM 엔드포인트](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)로 [CreateUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html) 요청을 전송하여 IAM 사용자를 생성합니다.

1. [IAM 엔드포인트](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)로 [AttachUserPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachUserPolicy.html) 요청을 전송하여 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess)를 IAM 사용자에게 연결합니다. 이 단계를 반복하여 필요에 따라 다른 관리형 또는 사용자 지정 정책을 사용자에게 연결할 수 있습니다.
**참고**  
보안 모범 사례로 IAM 정책을 IAM 사용자에게 연결하여 Amazon Bedrock API 키 사용을 제한하는 것이 좋습니다. 시간 제한 정책 및 키를 사용할 수 있는 IP 주소 제한의 예제는 [IAM 사용자에게 인라인 정책을 연결하여 액세스 키 사용 제어](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-keys_inline-policy.html)를 참조하세요.

1. [IAM 엔드포인트](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)로 [CreateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html.html) 요청을 보내고 `bedrock.amazonaws.com`을 `ServiceName`으로 지정하여 장기 Amazon Bedrock API 키를 생성합니다.
   + 응답에 반환된 `ServiceApiKeyValue`는 장기 Amazon Bedrock API 키입니다.
   + 응답에 반환된 `ServiceSpecificCredentialId`를 사용하여 키와 관련된 API 작업을 수행할 수 있습니다.

장기 Amazon Bedrock API 키를 생성하는 방법을 알아보려면 원하는 방법의 탭을 선택한 후 다음 단계를 따릅니다.

------
#### [ CLI ]

장기 Amazon Bedrock API 키를 생성하려면 AWS Identity and Access Management API 작업을 사용합니다. 먼저 사전 조건을 충족했는지 확인합니다.

**사전 조건**  
설정에서가 자격 AWS 증명을 자동으로 인식 AWS CLI 하도록 허용하는지 확인합니다. 자세한 내용은 [AWS CLI설정 구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)을 참조하세요.

터미널을 열고 다음 명령을 실행합니다.

1. IAM 사용자를 생성합니다. 이름을 원하는 이름으로 바꿀 수 있습니다.

   ```
   aws iam create-user --user-name bedrock-api-user
   ```

1. [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess)를 사용자에게 연결합니다. API 키에 추가하려는 다른 AWS관리형 또는 사용자 지정 정책의 ARNs을 사용하여이 단계를 반복할 수 있습니다.

   ```
   aws iam attach-user-policy --user-name bedrock-api-user --policy-arn arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess
   ```

1. 장기 Amazon Bedrock API 키를 생성하여 {{${NUMBER-OF-DAYS}}}를 키를 유지할 일수로 바꿉니다.

   ```
   aws iam create-service-specific-credential \
       --user-name bedrock-api-user \
       --service-name bedrock.amazonaws.com \
       --credential-age-days {{${NUMBER-OF-DAYS}}}
   ```

------
#### [ Python ]

장기 Amazon Bedrock API 키를 생성하려면 AWS Identity and Access Management API 작업을 사용합니다. 먼저 사전 조건을 충족했는지 확인합니다.

**사전 조건**  
설정을 통해 Python이 자격 AWS 증명을 자동으로 인식할 수 있는지 확인합니다. 자세한 내용은 [AWS CLI설정 구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)을 참조하세요.

다음 스크립트를 실행하여 IAM 사용자를 생성하고, Amazon Bedrock 작업을 수행할 권한을 연결하고, 사용자와 연결할 장기 Amazon Bedrock API 키를 생성합니다.

```
import boto3
from datetime import datetime, timedelta

# Replace with name for your IAM user
username = "bedrock-api-user"
# Add any AWS-managed or custom policies that you want to the user
bedrock_policies = [
    "arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess",        # Limited access
#    "arn:aws:iam::aws:policy/AmazonBedrockMarketplaceAccess",   # Optional: Access to Amazon Bedrock Marketplace actions
]
# Set the key expiration time to a number of your choice
expiration_time_in_days = 30

iam_client = boto3.client("iam")
    
# Create IAM user
user = iam_client.create_iam_user(username)

# Attach policies to user
for policy_arn in bedrock_policies:
    iam_client.attach_managed_policy(username, policy_arn)

# Create long-term Amazon Bedrock API key and return it
service_credentials = iam_client.create_service_specific_credential(
    user_name=username, 
    service_name="bedrock",
    credential_age_days=expiration_time_in_days
) 
api_key = service_credentials["ServiceApiKeyValue"]
print(api_key)
```

------

## 클라이언트 라이브러리를 사용하여 단기 Amazon Bedrock API 키 생성
<a name="api-keys-generate-short-term"></a>

단기 키의 속성은 다음과 같습니다.
+ 다음 값 중 더 짧은 값에 대해 유효합니다.
  + 12시간
  + 키를 생성하는 데 사용되는 IAM 보안 주체가 생성한 세션의 기간
+ 키를 생성하는 데 사용되는 보안 주체에 연결된 권한을 상속합니다.
+ 생성한 AWS 리전에서만 사용할 수 있습니다.

장기 실행 애플리케이션의 경우 [aws-bedrock-token-generator](https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md) 클라이언트 라이브러리는 자격 증명을 새로 고칠 때 필요에 따라 새 Amazon Bedrock 단기 API 키를 생성할 수 있습니다. 자세한 내용은 [단기 Amazon Bedrock API 키의 자동 새로 고침 설정](#api-keys-refresh-short-term) 단원을 참조하십시오.

**사전 조건**
+ 키를 생성하는 데 사용하는 IAM 보안 주체가 Amazon Bedrock을 사용할 수 있는 적절한 권한으로 설정되어 있는지 확인합니다. 실험을 위해 AWS관리형 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 정책을 보안 주체에 연결할 수 있습니다. 자격 증명을 보호하기 위해 [IAM의 보안 모범 사례](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)를 참조할 수 있습니다.
+ 설정을 통해 Python이 자격 AWS 증명을 자동으로 인식할 수 있는지 확인합니다. 자격 증명을 검색하는 기본 방법은 정의된 계층 구조를 따릅니다. 특정 SDK 또는 [AWS SDK 및 도구의 표준화된 자격 증명 공급자](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html)의 도구에 대한 계층 구조를 볼 수 있습니다.
+ Amazon Bedrock 토큰 생성기를 설치합니다. 원하는 방법의 탭을 선택한 후 다음 단계를 따릅니다.

------
#### [ Python ]

터미널을 열고 다음 명령을 실행합니다.

```
pip install aws-bedrock-token-generator
```

------
#### [ Javascript ]

터미널을 열고 다음 명령을 실행합니다.

```
npm install @aws/bedrock-token-generator
```

------
#### [ Java ]

Maven을 사용한다면 `pom.xml`에 다음 종속성을 추가합니다.

```
<dependency>
    <groupId>software.amazon.bedrock</groupId>
    <artifactId>aws-bedrock-token-generator</artifactId>
    <version>1.1.0</version>
</dependency>
```

Gradle을 사용하는 경우 `build.gradle`에 다음을 추가합니다.

```
implementation 'software.amazon.bedrock:aws-bedrock-token-generator:1.1.0'
```

------

**예제**  
토큰 생성기를 사용하여 다양한 언어로 된 기본 자격 증명으로 단기 Amazon Bedrock API 키를 생성하는 예제를 보려면 선호하는 방법의 탭을 선택한 다음 단계를 따릅니다.

------
#### [ Python ]

```
from aws_bedrock_token_generator import provide_token

token = provide_token()
print(f"Token: {token}")
```

------
#### [ Javascript ]

```
import { getTokenProvider } from "@aws/bedrock-token-generator";

// Create a token provider that uses default credentials and region providers.
// You can configure it to use other credential providers.
const provideToken = getTokenProvider();

async function example() {
    
  const token = await provideToken();

  // Use the token for API calls. The token has a default expiration of 12 hour.
  // If the expiresInSeconds parameter is specified during token creation, the 
  // expiration can be configured up to a maximum of 12 hours. However, the actual 
  // token validity period will always be the minimum of the requested expiration 
  // time and the AWS credentials' expiry time
  console.log(`Bearer Token: ${token}`);
}
```

------
#### [ Java ]

```
import software.amazon.bedrock.token.BedrockTokenGenerator;

// Credentials and region will be picked up from the default provider chain
BedrockTokenGenerator tokenGenerator = BedrockTokenGenerator.builder().build();
tokenGenerator.getToken();
```

------

토큰을 생성할 때 다양한 사용 사례에 대한 추가 예제를 보려면 다음 링크를 참조하세요.
+ [Python](https://github.com/aws/aws-bedrock-token-generator-python/blob/main/README.md)
+ [Javascript](https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md)
+ [Java](https://github.com/aws/aws-bedrock-token-generator-java/blob/main/README.md)

## 단기 Amazon Bedrock API 키의 자동 새로 고침 설정
<a name="api-keys-refresh-short-term"></a>

`aws-bedrock-token-generator` 패키지의 도움을 받아 스크립트를 생성하여 현재 키가 만료될 때마다 새 단기 키를 프로그래밍 방식으로 재생성할 수 있습니다. 먼저 [클라이언트 라이브러리를 사용하여 단기 Amazon Bedrock API 키 생성](#api-keys-generate-short-term)에서 사전 조건을 충족했는지 확인합니다. 토큰을 검색하고 Converse 요청을 하는 예제 스크립트를 보려면 원하는 방법의 탭을 선택한 후 다음 단계를 따릅니다.

------
#### [ Python ]

```
from aws_bedrock_token_generator import provide_token
import requests

def get_new_token():
    url = "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/converse"
    payload = {
        "messages": [
            {
                "role": "user",
                "content": [{"text": "Hello"}]
            }
        ]
    }

    # Create a token provider that uses default credentials and region providers.
    # You can configure it to use other credential providers.
    # https://github.com/aws/aws-bedrock-token-generator-python/blob/main/README.md
    # It can be used for each API call as it is inexpensive.
    token = provide_token()

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }

    response = requests.post(url, headers=headers, json=payload)
    print(response.json())

if __name__ == "__main__":
    get_new_token()
```

------
#### [ Javascript ]

```
import { getTokenProvider } from "@aws/bedrock-token-generator";

// Create a token provider that uses default credentials and region providers.
// You can configure it to use other credential providers.
// https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md
// This can be created just once. Use await provideToken() to fetch the token
const provideToken = getTokenProvider();

async function example() {
    const url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/converse";
    const payload = {
        messages: [
            {
                role: "user",
                content: [{ text: "Hello" }]
            }
        ]
    };
    const headers = {
        "Content-Type": "application/json",
        // provideToken retrieves a valid token. It can be used for each API call as it is inexpensive.
        "Authorization": `Bearer ${await provideToken()}`
    };
    await fetch(url, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(payload)
    })
}
```

------
#### [ Java ]

```
package com.amazon.bedrocktoken;

import software.amazon.bedrock.token.BedrockTokenGenerator;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GetNewToken {
    public static void main(String[] args) throws Exception {
        // Use default credentials and region from environment/profile chain
        // Create a token generator that uses default credentials and region providers.
        // You can configure it to use other credential providers.
        // https://github.com/aws/aws-bedrock-token-generator-java/blob/main/README.md
        BedrockTokenGenerator tokenGenerator = BedrockTokenGenerator.builder().build();

        // getToken() retrieves a valid token. It can be used for each API call as it is inexpensive.
        String token = tokenGenerator.getToken();

        String url = "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/converse";
        String payload = "{\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": [{ \"text\": \"Hello\" }]\n" +
                "        }\n" +
                "    ]\n" +
                "}";

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + token)
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
```

------