KotlinSDK용를 사용하는 Amazon ECR 예제 - AWS SDK 코드 예제

AWS 문서 예제 리포지토리에서 더 많은 SDK GitHub AWS SDK 예제를 사용할 수 있습니다.

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

KotlinSDK용를 사용하는 Amazon ECR 예제

다음 코드 예제에서는 Amazon에서 Kotlin용를 사용하여 작업을 수행하고 일반적인 시나리오를 AWS SDK 구현하는 방법을 보여줍니다ECR.

기본 사항은 서비스 내에서 필수 작업을 수행하는 방법을 보여주는 코드 예제입니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접적으로 호출하는 방법을 보여주며 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.

각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 전체 소스 코드에 대한 링크가 포함되어 있습니다.

시작

다음 코드 예제에서는 Amazon를 시작하는 방법을 보여줍니다ECR.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import aws.sdk.kotlin.services.ecr.EcrClient import aws.sdk.kotlin.services.ecr.model.ListImagesRequest import kotlin.system.exitProcess suspend fun main(args: Array<String>) { val usage = """ Usage: <repositoryName> Where: repositoryName - The name of the Amazon ECR repository. """.trimIndent() if (args.size != 1) { println(usage) exitProcess(1) } val repoName = args[0] listImageTags(repoName) } suspend fun listImageTags(repoName: String?) { val listImages = ListImagesRequest { repositoryName = repoName } EcrClient { region = "us-east-1" }.use { ecrClient -> val imageResponse = ecrClient.listImages(listImages) imageResponse.imageIds?.forEach { imageId -> println("Image tag: ${imageId.imageTag}") } } }
  • 자세한 API 내용은 listImages의에서 AWS SDK Kotlin API 참조를 참조하세요.

기본 사항

다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • Amazon ECR리포지토리를 생성합니다.

  • 리포지토리 정책을 설정합니다.

  • 리포지토리를 검색합니다URIs.

  • Amazon ECR 권한 부여 토큰을 가져옵니다.

  • Amazon ECR리포지토리의 수명 주기 정책을 설정합니다.

  • Docker 이미지를 Amazon ECR리포지토리로 푸시합니다.

  • Amazon ECR리포지토리에 이미지가 있는지 확인합니다.

  • 계정의 Amazon ECR리포지토리를 나열하고 이에 대한 세부 정보를 가져옵니다.

  • Amazon 리포지토ECR리를 삭제합니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

Amazon ECR 기능을 보여주는 대화형 시나리오를 실행합니다.

import java.util.Scanner /** * Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html * * This code example requires an IAM Role that has permissions to interact with the Amazon ECR service. * * To create an IAM role, see: * * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html * * This code example requires a local docker image named echo-text. Without a local image, * this program will not successfully run. For more information including how to create the local * image, see: * * /getting_started_scenarios/ecr_scenario/README * */ val DASHES = String(CharArray(80)).replace("\u0000", "-") suspend fun main(args: Array<String>) { val usage = """ Usage: <iamRoleARN> <accountId> Where: iamRoleARN - The IAM role ARN that has the necessary permissions to access and manage the Amazon ECR repository. accountId - Your AWS account number. """.trimIndent() // if (args.size != 2) { // println(usage) // return // } var iamRole = "arn:aws:iam::814548047983:role/Admin" var localImageName: String var accountId = "814548047983" val ecrActions = ECRActions() val scanner = Scanner(System.`in`) println( """ The Amazon Elastic Container Registry (ECR) is a fully-managed Docker container registry service provided by AWS. It allows developers and organizations to securely store, manage, and deploy Docker container images. ECR provides a simple and scalable way to manage container images throughout their lifecycle, from building and testing to production deployment. The `EcrClient` service client that is part of the AWS SDK for Kotlin provides a set of methods to programmatically interact with the Amazon ECR service. This allows developers to automate the storage, retrieval, and management of container images as part of their application deployment pipelines. With ECR, teams can focus on building and deploying their applications without having to worry about the underlying infrastructure required to host and manage a container registry. This scenario walks you through how to perform key operations for this service. Let's get started... You have two choices: 1 - Run the entire program. 2 - Delete an existing Amazon ECR repository named echo-text (created from a previous execution of this program that did not complete). """.trimIndent(), ) while (true) { val input = scanner.nextLine() if (input.trim { it <= ' ' }.equals("1", ignoreCase = true)) { println("Continuing with the program...") println("") break } else if (input.trim { it <= ' ' }.equals("2", ignoreCase = true)) { val repoName = "echo-text" ecrActions.deleteECRRepository(repoName) return } else { // Handle invalid input. println("Invalid input. Please try again.") } } waitForInputToContinue(scanner) println(DASHES) println( """ 1. Create an ECR repository. The first task is to ensure we have a local Docker image named echo-text. If this image exists, then an Amazon ECR repository is created. An ECR repository is a private Docker container repository provided by Amazon Web Services (AWS). It is a managed service that makes it easy to store, manage, and deploy Docker container images. """.trimIndent(), ) // Ensure that a local docker image named echo-text exists. val doesExist = ecrActions.listLocalImages() val repoName: String if (!doesExist) { println("The local image named echo-text does not exist") return } else { localImageName = "echo-text" repoName = "echo-text" } val repoArn = ecrActions.createECRRepository(repoName).toString() println("The ARN of the ECR repository is $repoArn") waitForInputToContinue(scanner) println(DASHES) println( """ 2. Set an ECR repository policy. Setting an ECR repository policy using the `setRepositoryPolicy` function is crucial for maintaining the security and integrity of your container images. The repository policy allows you to define specific rules and restrictions for accessing and managing the images stored within your ECR repository. """.trimIndent(), ) waitForInputToContinue(scanner) ecrActions.setRepoPolicy(repoName, iamRole) waitForInputToContinue(scanner) println(DASHES) println( """ 3. Display ECR repository policy. Now we will retrieve the ECR policy to ensure it was successfully set. """.trimIndent(), ) waitForInputToContinue(scanner) val policyText = ecrActions.getRepoPolicy(repoName) println("Policy Text:") println(policyText) waitForInputToContinue(scanner) println(DASHES) println( """ 4. Retrieve an ECR authorization token. You need an authorization token to securely access and interact with the Amazon ECR registry. The `getAuthorizationToken` method of the `EcrAsyncClient` is responsible for securely accessing and interacting with an Amazon ECR repository. This operation is responsible for obtaining a valid authorization token, which is required to authenticate your requests to the ECR service. Without a valid authorization token, you would not be able to perform any operations on the ECR repository, such as pushing, pulling, or managing your Docker images. """.trimIndent(), ) waitForInputToContinue(scanner) ecrActions.getAuthToken() waitForInputToContinue(scanner) println(DASHES) println( """ 5. Get the ECR Repository URI. The URI of an Amazon ECR repository is important. When you want to deploy a container image to a container orchestration platform like Amazon Elastic Kubernetes Service (EKS) or Amazon Elastic Container Service (ECS), you need to specify the full image URI, which includes the ECR repository URI. This allows the container runtime to pull the correct container image from the ECR repository. """.trimIndent(), ) waitForInputToContinue(scanner) val repositoryURI: String? = ecrActions.getRepositoryURI(repoName) println("The repository URI is $repositoryURI") waitForInputToContinue(scanner) println(DASHES) println( """ 6. Set an ECR Lifecycle Policy. An ECR Lifecycle Policy is used to manage the lifecycle of Docker images stored in your ECR repositories. These policies allow you to automatically remove old or unused Docker images from your repositories, freeing up storage space and reducing costs. """.trimIndent(), ) waitForInputToContinue(scanner) val pol = ecrActions.setLifeCyclePolicy(repoName) println(pol) waitForInputToContinue(scanner) println(DASHES) println( """ 7. Push a docker image to the Amazon ECR Repository. The `pushImageCmd()` method pushes a local Docker image to an Amazon ECR repository. It sets up the Docker client by connecting to the local Docker host using the default port. It then retrieves the authorization token for the ECR repository by making a call to the AWS SDK. The method uses the authorization token to create an `AuthConfig` object, which is used to authenticate the Docker client when pushing the image. Finally, the method tags the Docker image with the specified repository name and image tag, and then pushes the image to the ECR repository using the Docker client. If the push operation is successful, the method prints a message indicating that the image was pushed to ECR. """.trimIndent(), ) waitForInputToContinue(scanner) ecrActions.pushDockerImage(repoName, localImageName) waitForInputToContinue(scanner) println(DASHES) println("8. Verify if the image is in the ECR Repository.") waitForInputToContinue(scanner) ecrActions.verifyImage(repoName, localImageName) waitForInputToContinue(scanner) println(DASHES) println("9. As an optional step, you can interact with the image in Amazon ECR by using the CLI.") println("Would you like to view instructions on how to use the CLI to run the image? (y/n)") val ans = scanner.nextLine().trim() if (ans.equals("y", true)) { val instructions = """ 1. Authenticate with ECR - Before you can pull the image from Amazon ECR, you need to authenticate with the registry. You can do this using the AWS CLI: aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin $accountId.dkr.ecr.us-east-1.amazonaws.com 2. Describe the image using this command: aws ecr describe-images --repository-name $repoName --image-ids imageTag=$localImageName 3. Run the Docker container and view the output using this command: docker run --rm $accountId.dkr.ecr.us-east-1.amazonaws.com/$repoName:$localImageName """ println(instructions) } waitForInputToContinue(scanner) println(DASHES) println("10. Delete the ECR Repository.") println( """ If the repository isn't empty, you must either delete the contents of the repository or use the force option (used in this scenario) to delete the repository and have Amazon ECR delete all of its contents on your behalf. """.trimIndent(), ) println("Would you like to delete the Amazon ECR Repository? (y/n)") val delAns = scanner.nextLine().trim { it <= ' ' } if (delAns.equals("y", ignoreCase = true)) { println("You selected to delete the AWS ECR resources.") waitForInputToContinue(scanner) ecrActions.deleteECRRepository(repoName) } println(DASHES) println("This concludes the Amazon ECR SDK scenario") println(DASHES) } private fun waitForInputToContinue(scanner: Scanner) { while (true) { println("") println("Enter 'c' followed by <ENTER> to continue:") val input = scanner.nextLine() if (input.trim { it <= ' ' }.equals("c", ignoreCase = true)) { println("Continuing with the program...") println("") break } else { // Handle invalid input. println("Invalid input. Please try again.") } } }

Amazon ECR SDK 메서드의 래퍼 클래스입니다.

import aws.sdk.kotlin.services.ecr.EcrClient import aws.sdk.kotlin.services.ecr.model.CreateRepositoryRequest import aws.sdk.kotlin.services.ecr.model.DeleteRepositoryRequest import aws.sdk.kotlin.services.ecr.model.DescribeImagesRequest import aws.sdk.kotlin.services.ecr.model.DescribeRepositoriesRequest import aws.sdk.kotlin.services.ecr.model.EcrException import aws.sdk.kotlin.services.ecr.model.GetRepositoryPolicyRequest import aws.sdk.kotlin.services.ecr.model.ImageIdentifier import aws.sdk.kotlin.services.ecr.model.RepositoryAlreadyExistsException import aws.sdk.kotlin.services.ecr.model.SetRepositoryPolicyRequest import aws.sdk.kotlin.services.ecr.model.StartLifecyclePolicyPreviewRequest import com.github.dockerjava.api.DockerClient import com.github.dockerjava.api.command.DockerCmdExecFactory import com.github.dockerjava.api.model.AuthConfig import com.github.dockerjava.core.DockerClientBuilder import com.github.dockerjava.netty.NettyDockerCmdExecFactory import java.io.IOException import java.util.Base64 class ECRActions { private var dockerClient: DockerClient? = null private fun getDockerClient(): DockerClient? { val osName = System.getProperty("os.name") if (osName.startsWith("Windows")) { // Make sure Docker Desktop is running. val dockerHost = "tcp://localhost:2375" // Use the Docker Desktop default port. val dockerCmdExecFactory: DockerCmdExecFactory = NettyDockerCmdExecFactory().withReadTimeout(20000).withConnectTimeout(20000) dockerClient = DockerClientBuilder.getInstance(dockerHost).withDockerCmdExecFactory(dockerCmdExecFactory).build() } else { dockerClient = DockerClientBuilder.getInstance().build() } return dockerClient } /** * Sets the lifecycle policy for the specified repository. * * @param repoName the name of the repository for which to set the lifecycle policy. */ suspend fun setLifeCyclePolicy(repoName: String): String? { val polText = """ { "rules": [ { "rulePriority": 1, "description": "Expire images older than 14 days", "selection": { "tagStatus": "any", "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 14 }, "action": { "type": "expire" } } ] } """.trimIndent() val lifecyclePolicyPreviewRequest = StartLifecyclePolicyPreviewRequest { lifecyclePolicyText = polText repositoryName = repoName } // Execute the request asynchronously. EcrClient { region = "us-east-1" }.use { ecrClient -> val response = ecrClient.startLifecyclePolicyPreview(lifecyclePolicyPreviewRequest) return response.lifecyclePolicyText } } /** * Retrieves the repository URI for the specified repository name. * * @param repoName the name of the repository to retrieve the URI for. * @return the repository URI for the specified repository name. */ suspend fun getRepositoryURI(repoName: String?): String? { require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" } val request = DescribeRepositoriesRequest { repositoryNames = listOf(repoName) } EcrClient { region = "us-east-1" }.use { ecrClient -> val describeRepositoriesResponse = ecrClient.describeRepositories(request) if (!describeRepositoriesResponse.repositories?.isEmpty()!!) { return describeRepositoriesResponse?.repositories?.get(0)?.repositoryUri } else { println("No repositories found for the given name.") return "" } } } /** * Retrieves the authorization token for Amazon Elastic Container Registry (ECR). * */ suspend fun getAuthToken() { EcrClient { 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.") } } } /** * Gets the repository policy for the specified repository. * * @param repoName the name of the repository. */ suspend fun getRepoPolicy(repoName: String?): String? { require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" } // Create the request val getRepositoryPolicyRequest = GetRepositoryPolicyRequest { repositoryName = repoName } EcrClient { region = "us-east-1" }.use { ecrClient -> val response = ecrClient.getRepositoryPolicy(getRepositoryPolicyRequest) val responseText = response.policyText return responseText } } /** * Sets the repository policy for the specified ECR repository. * * @param repoName the name of the ECR repository. * @param iamRole the IAM role to be granted access to the repository. */ suspend fun setRepoPolicy( repoName: String?, iamRole: String?, ) { val policyDocumentTemplate = """ { "Version" : "2012-10-17", "Statement" : [ { "Sid" : "new statement", "Effect" : "Allow", "Principal" : { "AWS" : "$iamRole" }, "Action" : "ecr:BatchGetImage" } ] } """.trimIndent() val setRepositoryPolicyRequest = SetRepositoryPolicyRequest { repositoryName = repoName policyText = policyDocumentTemplate } EcrClient { region = "us-east-1" }.use { ecrClient -> val response = ecrClient.setRepositoryPolicy(setRepositoryPolicyRequest) if (response != null) { println("Repository policy set successfully.") } } } /** * Creates an Amazon Elastic Container Registry (Amazon ECR) repository. * * @param repoName the name of the repository to create. * @return the Amazon Resource Name (ARN) of the created repository, or an empty string if the operation failed. * @throws RepositoryAlreadyExistsException if the repository exists. * @throws EcrException if an error occurs while creating the repository. */ suspend fun createECRRepository(repoName: String?): String? { val request = CreateRepositoryRequest { repositoryName = repoName } return try { EcrClient { region = "us-east-1" }.use { ecrClient -> val response = ecrClient.createRepository(request) response.repository?.repositoryArn } } catch (e: RepositoryAlreadyExistsException) { println("Repository already exists: $repoName") repoName?.let { getRepoARN(it) } } catch (e: EcrException) { println("An error occurred: ${e.message}") null } } suspend fun getRepoARN(repoName: String): String? { // Fetch the existing repository's ARN. val describeRequest = DescribeRepositoriesRequest { repositoryNames = listOf(repoName) } EcrClient { region = "us-east-1" }.use { ecrClient -> val describeResponse = ecrClient.describeRepositories(describeRequest) return describeResponse.repositories?.get(0)?.repositoryArn } } fun listLocalImages(): Boolean = try { val images = getDockerClient()?.listImagesCmd()?.exec() images?.any { image -> image.repoTags?.any { tag -> tag.startsWith("echo-text") } ?: false } ?: false } catch (ex: Exception) { println("ERROR: ${ex.message}") false } /** * Pushes a Docker image to an Amazon Elastic Container Registry (ECR) repository. * * @param repoName the name of the ECR repository to push the image to. * @param imageName the name of the Docker image. */ suspend fun pushDockerImage( repoName: String, imageName: String, ) { println("Pushing $imageName to $repoName will take a few seconds") val authConfig = getAuthConfig(repoName) EcrClient { region = "us-east-1" }.use { ecrClient -> val desRequest = DescribeRepositoriesRequest { repositoryNames = listOf(repoName) } val describeRepoResponse = ecrClient.describeRepositories(desRequest) val repoData = describeRepoResponse.repositories?.firstOrNull { it.repositoryName == repoName } ?: throw RuntimeException("Repository not found: $repoName") val tagImageCmd = getDockerClient()?.tagImageCmd("$imageName", "${repoData.repositoryUri}", imageName) if (tagImageCmd != null) { tagImageCmd.exec() } val pushImageCmd = repoData.repositoryUri?.let { dockerClient?.pushImageCmd(it) // ?.withTag("latest") ?.withAuthConfig(authConfig) } try { if (pushImageCmd != null) { pushImageCmd.start().awaitCompletion() } println("The $imageName was pushed to Amazon ECR") } catch (e: IOException) { throw RuntimeException(e) } } } /** * 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 { 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.") } } } /** * Deletes an ECR (Elastic Container Registry) repository. * * @param repoName the name of the repository to delete. */ suspend fun deleteECRRepository(repoName: String) { if (repoName.isNullOrEmpty()) { throw IllegalArgumentException("Repository name cannot be null or empty") } val repositoryRequest = DeleteRepositoryRequest { force = true repositoryName = repoName } EcrClient { region = "us-east-1" }.use { ecrClient -> ecrClient.deleteRepository(repositoryRequest) println("You have successfully deleted the $repoName repository") } } // Return an AuthConfig. private suspend fun getAuthConfig(repoName: String): AuthConfig { EcrClient { 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 val decodedToken = String(Base64.getDecoder().decode(token)) val password = decodedToken.substring(4) val request = DescribeRepositoriesRequest { repositoryNames = listOf(repoName) } val descrRepoResponse = ecrClient.describeRepositories(request) val repoData = descrRepoResponse.repositories?.firstOrNull { it.repositoryName == repoName } val registryURL: String = repoData?.repositoryUri?.split("/")?.get(0) ?: "" return AuthConfig() .withUsername("AWS") .withPassword(password) .withRegistryAddress(registryURL) } } }

작업

다음 코드 예시에서는 CreateRepository을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Creates an Amazon Elastic Container Registry (Amazon ECR) repository. * * @param repoName the name of the repository to create. * @return the Amazon Resource Name (ARN) of the created repository, or an empty string if the operation failed. * @throws RepositoryAlreadyExistsException if the repository exists. * @throws EcrException if an error occurs while creating the repository. */ suspend fun createECRRepository(repoName: String?): String? { val request = CreateRepositoryRequest { repositoryName = repoName } return try { EcrClient { region = "us-east-1" }.use { ecrClient -> val response = ecrClient.createRepository(request) response.repository?.repositoryArn } } catch (e: RepositoryAlreadyExistsException) { println("Repository already exists: $repoName") repoName?.let { getRepoARN(it) } } catch (e: EcrException) { println("An error occurred: ${e.message}") null } }
  • 자세한 API 내용은 CreateRepository의에서 AWS SDK Kotlin API 참조를 참조하세요.

다음 코드 예시에서는 DeleteRepository을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Deletes an ECR (Elastic Container Registry) repository. * * @param repoName the name of the repository to delete. */ suspend fun deleteECRRepository(repoName: String) { if (repoName.isNullOrEmpty()) { throw IllegalArgumentException("Repository name cannot be null or empty") } val repositoryRequest = DeleteRepositoryRequest { force = true repositoryName = repoName } EcrClient { region = "us-east-1" }.use { ecrClient -> ecrClient.deleteRepository(repositoryRequest) println("You have successfully deleted the $repoName repository") } }
  • 자세한 API 내용은 DeleteRepositoryAWS SDK Kotlin API 참조를 참조하세요.

다음 코드 예시에서는 DescribeImages을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * 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 { 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 내용은 DescribeImagesAWS SDK Kotlin API 참조를 참조하세요.

다음 코드 예시에서는 DescribeRepositories을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Retrieves the repository URI for the specified repository name. * * @param repoName the name of the repository to retrieve the URI for. * @return the repository URI for the specified repository name. */ suspend fun getRepositoryURI(repoName: String?): String? { require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" } val request = DescribeRepositoriesRequest { repositoryNames = listOf(repoName) } EcrClient { region = "us-east-1" }.use { ecrClient -> val describeRepositoriesResponse = ecrClient.describeRepositories(request) if (!describeRepositoriesResponse.repositories?.isEmpty()!!) { return describeRepositoriesResponse?.repositories?.get(0)?.repositoryUri } else { println("No repositories found for the given name.") return "" } } }

다음 코드 예시에서는 GetAuthorizationToken을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Retrieves the authorization token for Amazon Elastic Container Registry (ECR). * */ suspend fun getAuthToken() { EcrClient { 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.") } } }

다음 코드 예시에서는 GetRepositoryPolicy을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Gets the repository policy for the specified repository. * * @param repoName the name of the repository. */ suspend fun getRepoPolicy(repoName: String?): String? { require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" } // Create the request val getRepositoryPolicyRequest = GetRepositoryPolicyRequest { repositoryName = repoName } EcrClient { region = "us-east-1" }.use { ecrClient -> val response = ecrClient.getRepositoryPolicy(getRepositoryPolicyRequest) val responseText = response.policyText return responseText } }

다음 코드 예시에서는 PushImageCmd을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Pushes a Docker image to an Amazon Elastic Container Registry (ECR) repository. * * @param repoName the name of the ECR repository to push the image to. * @param imageName the name of the Docker image. */ suspend fun pushDockerImage( repoName: String, imageName: String, ) { println("Pushing $imageName to $repoName will take a few seconds") val authConfig = getAuthConfig(repoName) EcrClient { region = "us-east-1" }.use { ecrClient -> val desRequest = DescribeRepositoriesRequest { repositoryNames = listOf(repoName) } val describeRepoResponse = ecrClient.describeRepositories(desRequest) val repoData = describeRepoResponse.repositories?.firstOrNull { it.repositoryName == repoName } ?: throw RuntimeException("Repository not found: $repoName") val tagImageCmd = getDockerClient()?.tagImageCmd("$imageName", "${repoData.repositoryUri}", imageName) if (tagImageCmd != null) { tagImageCmd.exec() } val pushImageCmd = repoData.repositoryUri?.let { dockerClient?.pushImageCmd(it) // ?.withTag("latest") ?.withAuthConfig(authConfig) } try { if (pushImageCmd != null) { pushImageCmd.start().awaitCompletion() } println("The $imageName was pushed to Amazon ECR") } catch (e: IOException) { throw RuntimeException(e) } } }
  • 자세한 API 내용은 PushImageCmd의에서 AWS SDK Kotlin API 참조를 참조하세요.

다음 코드 예시에서는 SetRepositoryPolicy을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Sets the repository policy for the specified ECR repository. * * @param repoName the name of the ECR repository. * @param iamRole the IAM role to be granted access to the repository. */ suspend fun setRepoPolicy( repoName: String?, iamRole: String?, ) { val policyDocumentTemplate = """ { "Version" : "2012-10-17", "Statement" : [ { "Sid" : "new statement", "Effect" : "Allow", "Principal" : { "AWS" : "$iamRole" }, "Action" : "ecr:BatchGetImage" } ] } """.trimIndent() val setRepositoryPolicyRequest = SetRepositoryPolicyRequest { repositoryName = repoName policyText = policyDocumentTemplate } EcrClient { region = "us-east-1" }.use { ecrClient -> val response = ecrClient.setRepositoryPolicy(setRepositoryPolicyRequest) if (response != null) { println("Repository policy set successfully.") } } }

다음 코드 예시에서는 StartLifecyclePolicyPreview을 사용하는 방법을 보여 줍니다.

SDK Kotlin용
참고

더 많은 기능이 있습니다 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * 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 { 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.") } } }