|
15 | 15 | # ANY KIND, either express or implied. See the License for the specific |
16 | 16 | # language governing permissions and limitations under the License. |
17 | 17 |
|
| 18 | +import json |
18 | 19 | import logging |
19 | 20 | import os |
20 | 21 | from typing import Dict, List, Optional |
21 | 22 |
|
22 | 23 | import boto3 |
| 24 | +import botocore.exceptions |
23 | 25 | import click |
24 | 26 |
|
25 | 27 | from samcli.commands.deploy import exceptions as deploy_exceptions |
|
39 | 41 |
|
40 | 42 | LOG = logging.getLogger(__name__) |
41 | 43 |
|
| 44 | +_SAM_ECR_POLICY_SID = "SAMCliLambdaECRAccess" |
| 45 | + |
| 46 | +_LAMBDA_ECR_POLICY_STATEMENT = { |
| 47 | + "Sid": _SAM_ECR_POLICY_SID, |
| 48 | + "Effect": "Allow", |
| 49 | + "Principal": {"Service": "lambda.amazonaws.com"}, |
| 50 | + "Action": [ |
| 51 | + "ecr:GetDownloadUrlForLayer", |
| 52 | + "ecr:BatchGetImage", |
| 53 | + "ecr:GetRepositoryPolicy", |
| 54 | + ], |
| 55 | +} |
| 56 | + |
42 | 57 |
|
43 | 58 | class DeployContext: |
44 | 59 | MSG_SHOWCASE_CHANGESET = "\nChangeset created successfully. {changeset_id}\n" |
@@ -151,6 +166,16 @@ def run(self): |
151 | 166 |
|
152 | 167 | self.deployer = Deployer(cloudformation_client, client_sleep=self.poll_delay) |
153 | 168 |
|
| 169 | + if self.image_repositories or self.image_repository: |
| 170 | + ecr_client = boto3.client( |
| 171 | + "ecr", region_name=self.region if self.region else None, config=boto_config |
| 172 | + ) |
| 173 | + _ensure_ecr_lambda_pull_policy( |
| 174 | + ecr_client, |
| 175 | + self.image_repositories if isinstance(self.image_repositories, dict) else None, |
| 176 | + self.image_repository or None, |
| 177 | + ) |
| 178 | + |
154 | 179 | region = s3_client._client_config.region_name if s3_client else self.region # pylint: disable=W0212 |
155 | 180 | display_parameter_overrides = hide_noecho_parameter_overrides(template_dict, self.parameter_overrides) |
156 | 181 | print_deploy_args( |
@@ -334,3 +359,102 @@ def merge_parameters(template_dict: Dict, parameter_overrides: Dict) -> List[Dic |
334 | 359 | parameter_values.append(obj) |
335 | 360 |
|
336 | 361 | return parameter_values |
| 362 | + |
| 363 | + |
| 364 | + |
| 365 | +def _extract_ecr_repo_name(ecr_uri: str) -> str: |
| 366 | + """ |
| 367 | + Extract the ECR repository name from a full ECR URI. |
| 368 | +
|
| 369 | + Examples |
| 370 | + -------- |
| 371 | + 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo:latest -> my-repo |
| 372 | + 123456789012.dkr.ecr.us-east-1.amazonaws.com/org/my-repo:v1 -> org/my-repo |
| 373 | + """ |
| 374 | + parts = ecr_uri.split("/", 1) |
| 375 | + repo_with_tag = parts[1] if len(parts) > 1 else parts[0] |
| 376 | + return repo_with_tag.split(":")[0] |
| 377 | + |
| 378 | + |
| 379 | +def _ensure_ecr_lambda_pull_policy( |
| 380 | + ecr_client, |
| 381 | + image_repositories: Optional[Dict[str, str]], |
| 382 | + image_repository: Optional[str], |
| 383 | +) -> None: |
| 384 | + """ |
| 385 | + Pre-set Lambda pull permissions on all ECR repositories referenced by |
| 386 | + --image-repositories / --image-repository before the CloudFormation |
| 387 | + changeset is created. |
| 388 | +
|
| 389 | + This prevents a race condition where CloudFormation's concurrent Lambda |
| 390 | + resource creation calls SetRepositoryPolicy in parallel, overwriting each |
| 391 | + other and causing intermittent 403 access errors (GitHub issue #8190). |
| 392 | + """ |
| 393 | + if not image_repositories and not image_repository: |
| 394 | + return |
| 395 | + |
| 396 | + uris = list((image_repositories or {}).values()) |
| 397 | + if image_repository: |
| 398 | + uris.append(image_repository) |
| 399 | + |
| 400 | + unique_repo_names = {_extract_ecr_repo_name(uri) for uri in uris if uri} |
| 401 | + |
| 402 | + for repo_name in unique_repo_names: |
| 403 | + _upsert_ecr_lambda_policy(ecr_client, repo_name) |
| 404 | + |
| 405 | + |
| 406 | +def _upsert_ecr_lambda_policy(ecr_client, repo_name: str) -> None: |
| 407 | + """ |
| 408 | + Idempotently upsert a Lambda pull policy statement on a single ECR repo. |
| 409 | +
|
| 410 | + Soft-fails on AccessDenied so users who have manually pre-configured |
| 411 | + policies or whose IAM principal lacks ecr:SetRepositoryPolicy are not blocked. |
| 412 | + """ |
| 413 | + # Step 1: Fetch current policy (if any) |
| 414 | + existing_statements = [] |
| 415 | + try: |
| 416 | + response = ecr_client.get_repository_policy(repositoryName=repo_name) |
| 417 | + policy_doc = json.loads(response.get("policyText", "{}")) |
| 418 | + existing_statements = policy_doc.get("Statement", []) |
| 419 | + except ecr_client.exceptions.RepositoryPolicyNotFoundException: |
| 420 | + existing_statements = [] |
| 421 | + except botocore.exceptions.ClientError as ex: |
| 422 | + error_code = ex.response.get("Error", {}).get("Code", "") |
| 423 | + if error_code in ("AccessDeniedException", "AuthorizationErrorException"): |
| 424 | + LOG.warning( |
| 425 | + "Could not read ECR policy for '%s' (access denied). " |
| 426 | + "Skipping — ensure ecr:GetRepositoryPolicy permission to prevent " |
| 427 | + "intermittent Lambda 403 errors during deployment.", |
| 428 | + repo_name, |
| 429 | + ) |
| 430 | + return |
| 431 | + raise deploy_exceptions.ECRPolicySetError(repo_name=repo_name, msg=str(ex)) from ex |
| 432 | + |
| 433 | + # Step 2: Remove any existing SAM-owned statement (idempotent upsert) |
| 434 | + filtered = [s for s in existing_statements if s.get("Sid") != _SAM_ECR_POLICY_SID] |
| 435 | + |
| 436 | + # Step 3: Build merged policy |
| 437 | + merged_policy = { |
| 438 | + "Version": "2012-10-17", |
| 439 | + "Statement": filtered + [_LAMBDA_ECR_POLICY_STATEMENT], |
| 440 | + } |
| 441 | + |
| 442 | + # Step 4: Write the merged policy back |
| 443 | + try: |
| 444 | + ecr_client.set_repository_policy( |
| 445 | + repositoryName=repo_name, |
| 446 | + policyText=json.dumps(merged_policy), |
| 447 | + force=False, |
| 448 | + ) |
| 449 | + LOG.info("Pre-set Lambda pull policy on ECR repository '%s'", repo_name) |
| 450 | + except botocore.exceptions.ClientError as ex: |
| 451 | + error_code = ex.response.get("Error", {}).get("Code", "") |
| 452 | + if error_code in ("AccessDeniedException", "AuthorizationErrorException"): |
| 453 | + LOG.warning( |
| 454 | + "Could not set ECR policy for '%s' (access denied). " |
| 455 | + "Skipping — ensure ecr:SetRepositoryPolicy permission to prevent " |
| 456 | + "intermittent Lambda 403 errors during deployment.", |
| 457 | + repo_name, |
| 458 | + ) |
| 459 | + return |
| 460 | + raise deploy_exceptions.ECRPolicySetError(repo_name=repo_name, msg=str(ex)) from ex |
0 commit comments