/**
* 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.
*/publicvoidsetRepoPolicy(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;
} elseif (cause instanceof EcrException) {throw (EcrException) cause;
} else{
String errorMessage = "Unexpected error: " + cause.getMessage();
thrownew RuntimeException(errorMessage, cause);
}
}
});
response.join();
}
API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「SetRepositoryPolicy」を参照してください。
classECRWrapper:def__init__(self, ecr_client: client):
self.ecr_client = ecr_client
@classmethoddeffrom_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)
defset_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)
raiseelse:
logger.error(
"Couldn't set repository policy for repository %s. Here's why %s",
repository_name,
err.response["Error"]["Message"],
)
raise
IAM ロールにダウンロードアクセスを付与する例。
defgrant_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": "2008-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 リファレンスの「SetRepositoryPolicy」を参照してください。