AWS SDK 또는 CLI로 GetAuthorizationToken 사용하기
AWS SDK 또는 CLI로 GetAuthorizationToken 사용하기
다음 코드 예제는 AWS SDK와 CLI에서 GetAuthorizationToken을 사용하는 방법을 보여줍니다. 액션 예제는 더 큰 프로그램에서 발췌한 코드 조각이므로 문맥 안에서 실행해야 합니다. 이 액션은 다음 코드 예제에서 문맥과 함께 살펴볼 수 있습니다: 기본 익히기(Learn the basics).
출처: 문서
본문
CLI
AWS CLI
기본 레지스트리의 인증 토큰 가져오기
다음 get-authorization-token 예제 명령은 기본 레지스트리의 인증 토큰을 가져옵니다.
aws ecr get-authorization-token
출력:
{
"authorizationData": [
{
"authorizationToken": "QVdTOkN...",
"expiresAt": 1448875853.241,
"proxyEndpoint": "https://123456789012.dkr.ecr.us-west-2.amazonaws.com"
}
]
}
API 세부 정보는 AWS CLI Command Reference의 GetAuthorizationToken를 참조하세요.
Java
SDK for Java 2.x
참고: GitHub에 더 많은 내용이 있습니다. 전체 예제를 찾아 설정하고 실행하는 방법은 AWS Code Examples Repository에서 확인하세요.
/**
* Retrieves the authorization token for Amazon Elastic Container Registry (ECR).
* This method makes an asynchronous call to the ECR client to retrieve the authorization token.
* If the operation is successful, the method prints the token to the console.
* If an exception occurs, the method handles the exception and prints the error message.
*
* @throws EcrException if there is an error retrieving the authorization token from ECR.
* @throws RuntimeException if there is an unexpected error during the operation.
*/
public void getAuthToken() {
CompletableFuture<GetAuthorizationTokenResponse> response = getAsyncClient().getAuthorizationToken();
response.whenComplete((authorizationTokenResponse, ex) -> {
if (authorizationTokenResponse != null) {
AuthorizationData authorizationData = authorizationTokenResponse.authorizationData().get(0);
String token = authorizationData.authorizationToken();
if (!token.isEmpty()) {
System.out.println("The token was successfully retrieved.");
}
} else {
if (ex.getCause() instanceof EcrException) {
throw (EcrException) ex.getCause();
} else {
String errorMessage = "Unexpected error occurred: " + ex.getMessage();
throw new RuntimeException(errorMessage, ex); // Rethrow the exception
}
}
});
response.join();
}
API 세부 정보는 AWS SDK for Java 2.x API Reference의 GetAuthorizationToken를 참조하세요.
Kotlin
SDK for Kotlin
참고: GitHub에 더 많은 내용이 있습니다. 전체 예제를 찾아 설정하고 실행하는 방법은 AWS Code Examples Repository에서 확인하세요.
/**
* Retrieves the authorization token for Amazon Elastic Container Registry (ECR).
*
*/
suspend fun getAuthToken() {
EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
// Retrieve the authorization token for ECR.
val response = ecrClient.getAuthorizationToken()
val authorizationData = response.authorizationData?.get(0)
val token = authorizationData?.authorizationToken
if (token != null) {
println("The token was successfully retrieved.")
}
}
}
API 세부 정보는 AWS SDK for Kotlin API reference의 GetAuthorizationToken를 참조하세요.
Python
SDK for Python (Boto3)
참고: GitHub에 더 많은 내용이 있습니다. 전체 예제를 찾아 설정하고 실행하는 방법은 AWS Code Examples Repository에서 확인하세요.
class ECRWrapper:
def __init__(self, ecr_client: client):
self.ecr_client = ecr_client
@classmethod
def from_client(cls) -> "ECRWrapper":
"""
Creates a ECRWrapper instance with a default Amazon ECR client.
:return: An instance of ECRWrapper initialized with the default Amazon ECR client.
"""
ecr_client = boto3.client("ecr")
return cls(ecr_client)
def get_authorization_token(self) -> str:
"""
Gets an authorization token for an ECR repository.
:return: The authorization token.
"""
try:
response = self.ecr_client.get_authorization_token()
return response["authorizationData"][0]["authorizationToken"]
except ClientError as err:
logger.error(
"Couldn't get authorization token. Here's why %s",
err.response["Error"]["Message"],
)
raise
API 세부 정보는 AWS SDK for Python (Boto3) API Reference의 GetAuthorizationToken를 참조하세요.
SAP ABAP
SDK for SAP ABAP
참고: GitHub에 더 많은 내용이 있습니다. 전체 예제를 찾아 설정하고 실행하는 방법은 AWS Code Examples Repository에서 확인하세요.
TRY.
oo_result = lo_ecr->getauthorizationtoken( ).
DATA(lt_auth_data) = oo_result->get_authorizationdata( ).
IF lines( lt_auth_data ) > 0.
READ TABLE lt_auth_data INDEX 1 INTO DATA(lo_auth_data).
DATA(lv_token) = lo_auth_data->get_authorizationtoken( ).
MESSAGE 'Authorization token retrieved.' TYPE 'I'.
ENDIF.
CATCH /aws1/cx_ecrserverexception.
MESSAGE 'Server exception occurred.' TYPE 'I'.
ENDTRY.
API 세부 정보는 AWS SDK for SAP ABAP API reference의 GetAuthorizationToken를 참조하세요.
AWS SDK 개발자 가이드와 코드 예제의 전체 목록은 AWS SDK로 Amazon ECR 사용하기를 참조하세요. 이 주제에는 시작하기 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.