AWS SDK 또는 CLI로 StartLifecyclePolicyPreview 사용하기

AWS SDK 또는 CLI로 StartLifecyclePolicyPreview 사용하기

다음 코드 예제는 AWS SDK와 CLI에서 StartLifecyclePolicyPreview를 사용하는 방법을 보여줍니다. 액션 예제는 더 큰 프로그램에서 발췌한 코드 조각이므로 문맥 안에서 실행해야 합니다. 이 액션은 다음 코드 예제에서 문맥과 함께 살펴볼 수 있습니다: 기본 익히기(Learn the basics).

출처: 문서

본문

CLI

AWS CLI

수명 주기 정책 미리보기 만들기

다음 start-lifecycle-policy-preview 예제는 지정된 리포지토리에 대해 JSON 파일로 정의된 수명 주기 정책 미리보기를 생성합니다.

aws ecr start-lifecycle-policy-preview \
    --repository-name "project-a/amazon-ecs-sample" \
    --lifecycle-policy-text "file://policy.json"

policy.json 내용:

{
   "rules": [
       {
           "rulePriority": 1,
           "description": "Expire images older than 14 days",
           "selection": {
               "tagStatus": "untagged",
               "countType": "sinceImagePushed",
               "countUnit": "days",
               "countNumber": 14
           },
           "action": {
               "type": "expire"
           }
       }
   ]
}

출력:

{
   "registryId": "012345678910",
   "repositoryName": "project-a/amazon-ecs-sample",
   "lifecyclePolicyText": "{\n    \"rules\": [\n        {\n            \"rulePriority\": 1,\n            \"description\": \"Expire images older than 14 days\",\n            \"selection\": {\n                \"tagStatus\": \"untagged\",\n                \"countType\": \"sinceImagePushed\",\n                \"countUnit\": \"days\",\n                \"countNumber\": 14\n            },\n            \"action\": {\n                \"type\": \"expire\"\n            }\n        }\n    ]\n}\n",
   "status": "IN_PROGRESS"
}

API 세부 정보는 AWS CLI Command Reference의 StartLifecyclePolicyPreview를 참조하세요.

Java

SDK for Java 2.x

참고: GitHub에 더 많은 내용이 있습니다. 전체 예제를 찾아 설정하고 실행하는 방법은 AWS Code Examples Repository에서 확인하세요.

    /**
     * Verifies the existence of an image in an Amazon Elastic Container Registry (Amazon ECR) repository asynchronously.
     *
     * @param repositoryName The name of the Amazon ECR repository.
     * @param imageTag       The tag of the image to verify.
     * @throws EcrException             if there is an error retrieving the image information from Amazon ECR.
     * @throws CompletionException      if the asynchronous operation completes exceptionally.
     */
    public void verifyImage(String repositoryName, String imageTag) {
        DescribeImagesRequest request = DescribeImagesRequest.builder()
            .repositoryName(repositoryName)
            .imageIds(ImageIdentifier.builder().imageTag(imageTag).build())
            .build();

        CompletableFuture<DescribeImagesResponse> response = getAsyncClient().describeImages(request);
        response.whenComplete((describeImagesResponse, ex) -> {
            if (ex != null) {
                if (ex instanceof CompletionException) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof EcrException) {
                        throw (EcrException) cause;
                    } else {
                        throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                    }
                } else {
                    throw new RuntimeException("Unexpected error: " + ex.getCause());
                }
            } else if (describeImagesResponse != null && !describeImagesResponse.imageDetails().isEmpty()) {
                System.out.println("Image is present in the repository.");
            } else {
                System.out.println("Image is not present in the repository.");
            }
        });

        // Wait for the CompletableFuture to complete.
        response.join();
    }

API 세부 정보는 AWS SDK for Java 2.x API Reference의 StartLifecyclePolicyPreview를 참조하세요.

Kotlin

SDK for Kotlin

참고: GitHub에 더 많은 내용이 있습니다. 전체 예제를 찾아 설정하고 실행하는 방법은 AWS Code Examples Repository에서 확인하세요.

    /**
     * Verifies the existence of an image in an Amazon Elastic Container Registry (Amazon ECR) repository asynchronously.
     *
     * @param repositoryName The name of the Amazon ECR repository.
     * @param imageTag       The tag of the image to verify.
     */
    suspend fun verifyImage(
        repoName: String?,
        imageTagVal: String?,
    ) {
        require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" }
        require(!(imageTagVal == null || imageTagVal.isEmpty())) { "Image tag cannot be null or empty" }

        val imageId =
            ImageIdentifier {
                imageTag = imageTagVal
            }
        val request =
            DescribeImagesRequest {
                repositoryName = repoName
                imageIds = listOf(imageId)
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val describeImagesResponse = ecrClient.describeImages(request)
            if (describeImagesResponse != null && !describeImagesResponse.imageDetails?.isEmpty()!!) {
                println("Image is present in the repository.")
            } else {
                println("Image is not present in the repository.")
            }
        }
    }

API 세부 정보는 AWS SDK for Kotlin API reference의 StartLifecyclePolicyPreview를 참조하세요.

AWS SDK 개발자 가이드와 코드 예제의 전체 목록은 AWS SDK로 Amazon ECR 사용하기를 참조하세요. 이 주제에는 시작하기 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.

더 알아보기 (Learn more)