AWS SDK 또는 CLI로 SetRepositoryPolicy 사용하기

AWS SDK 또는 CLI로 SetRepositoryPolicy 사용하기

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

출처: 문서

본문

CLI

AWS CLI

리포지토리의 정책 설정하기

다음 set-repository-policy 예제는 파일에 들어 있는 리포지토리 정책을 cluster-autoscaler 리포지토리에 연결합니다.

aws ecr set-repository-policy \
    --repository-name cluster-autoscaler \
    --policy-text file://my-policy.json

my-policy.json 내용:

{
    "Version":"2012-10-17",
    "Statement" : [
        {
            "Sid" : "allow public pull",
            "Effect" : "Allow",
            "Principal" : "*",
            "Action" : [
                "ecr:BatchCheckLayerAvailability",
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer"
            ]
        }
    ]
}

출력:

{
    "registryId": "012345678910",
    "repositoryName": "cluster-autoscaler",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"allow public pull\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : \"*\",\n    \"Action\" : [ \"ecr:BatchCheckLayerAvailability\", \"ecr:BatchGetImage\", \"ecr:GetDownloadUrlForLayer\" ]\n  } ]\n}"
}

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

Java

SDK for Java 2.x

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

/**
     * 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.
     * @throws RepositoryPolicyNotFoundException if the repository policy does not exist.
     * @throws EcrException                      if there is an unexpected error setting the repository policy.
     */
    public void setRepoPolicy(String repoName, String iamRole) {
        /*
          This example policy document grants the specified AWS principal the permission to perform the
          `ecr:BatchGetImage` action. This policy is designed to allow the specified principal
          to retrieve Docker images from the ECR repository.
         */
        String policyDocumentTemplate = """
            {
             "Version":"2012-10-17",
             "Statement" : [ {
               "Sid" : "new statement",
               "Effect" : "Allow",
               "Principal" : {
                 "AWS" : "%s"
               },
               "Action" : "ecr:BatchGetImage"
             } ]
            }
             """;

        String policyDocument = String.format(policyDocumentTemplate, iamRole);
        SetRepositoryPolicyRequest setRepositoryPolicyRequest = SetRepositoryPolicyRequest.builder()
            .repositoryName(repoName)
            .policyText(policyDocument)
            .build();

        CompletableFuture<SetRepositoryPolicyResponse> response = getAsyncClient().setRepositoryPolicy(setRepositoryPolicyRequest);
        response.whenComplete((resp, ex) -> {
            if (resp != null) {
                System.out.println("Repository policy set successfully.");
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof RepositoryPolicyNotFoundException) {
                    throw (RepositoryPolicyNotFoundException) cause;
                } else if (cause instanceof EcrException) {
                    throw (EcrException) cause;
                } else {
                    String errorMessage = "Unexpected error: " + cause.getMessage();
                    throw new RuntimeException(errorMessage, cause);
                }
            }
        });
        response.join();
    }

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

Kotlin

SDK for Kotlin

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

/**
     * 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.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val response = ecrClient.setRepositoryPolicy(setRepositoryPolicyRequest)
            if (response != null) {
                println("Repository policy set successfully.")
            }
        }
    }

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

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 set_repository_policy(self, repository_name: str, policy_text: str):
        """
        Sets the policy for an ECR repository.

        :param repository_name: The name of the repository to set the policy for.
        :param policy_text: The policy text to set.
        """
        try:
            self.ecr_client.set_repository_policy(
                repositoryName=repository_name, policyText=policy_text
            )
            print(f"Set repository policy for repository {repository_name}.")
        except ClientError as err:
            if err.response["Error"]["Code"] == "RepositoryPolicyNotFoundException":
                logger.error("Repository does not exist. %s.", repository_name)
                raise
            else:
                logger.error(
                    "Couldn't set repository policy for repository %s. Here's why %s",
                    repository_name,
                    err.response["Error"]["Message"],
                )
                raise

IAM 역할에 다운로드 권한을 부여하는 예제:

def grant_role_download_access(self, role_arn: str):
        """
        Grants the specified role access to download images from the ECR repository.

        :param role_arn: The ARN of the role to grant access to.
        """
        policy_json = {
            "Version":"2012-10-17",
            "Statement": [
                {
                    "Sid": "AllowDownload",
                    "Effect": "Allow",
                    "Principal": {"AWS": role_arn},
                    "Action": ["ecr:BatchGetImage"],
                }
            ],
        }

        self.ecr_wrapper.set_repository_policy(
            self.repository_name, json.dumps(policy_json)
        )

API 세부 정보는 AWS SDK for Python (Boto3) API Reference의 SetRepositoryPolicy를 참조하세요.

SAP ABAP

SDK for SAP ABAP

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

TRY.
        " iv_repository_name = 'my-repository'
        " iv_policy_text = '{"Version":"2012-10-17","Statement":[...]}'
        lo_ecr->setrepositorypolicy(
          iv_repositoryname = iv_repository_name
          iv_policytext = iv_policy_text ).
        MESSAGE |Policy set for repository { iv_repository_name }.| TYPE 'I'.
      CATCH /aws1/cx_ecrrepositorynotfndex.
        MESSAGE 'Repository not found.' TYPE 'I'.
    ENDTRY.

API 세부 정보는 AWS SDK for SAP ABAP API reference의 SetRepositoryPolicy를 참조하세요.

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

더 알아보기 (Learn more)