Error while updating ECR permission using boto3 client

Question:

We are trying to update the permission of an ECR repository using boto3 sdk.

import json
import boto3

access_key = "*******"
secret_access = "*******"
ecr_repo_name = 'repo-name'

client = boto3.client('ecr', region_name="eu-west-1",
                      aws_access_key_id=access_key,
                      aws_secret_access_key=secret_access)

single_template = {
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "ECR_cross_account_access",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<account_id>:root"
            },
            "Action": [
                "ecr:BatchCheckLayerAvailability",
                "ecr:BatchGetImage",
                "ecr:CompleteLayerUpload",
                "ecr:GetDownloadUrlForLayer",
                "ecr:InitiateLayerUpload",
                "ecr:PutImage",
                "ecr:UploadLayerPart"
            ]
        }
    ]
}

response = client.put_registry_policy(policyText=json.dumps(single_template))
print(response)

We are getting the following error.

Traceback (most recent call last):
  File "miscs/update_ecr_policy.py", line 89, in <module>
    response = client.put_registry_policy(policyText=json.dumps(single_template))
  File "/home/nandha/projects/venv3/lib/python3.7/site-packages/botocore/client.py", line 401, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/home/nandha/projects/venv3/lib/python3.7/site-packages/botocore/client.py", line 731, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.InvalidParameterException: An error occurred (InvalidParameterException) when calling the PutRegistryPolicy operation: Invalid parameter at 'PolicyText' failed to satisfy constraint: 'Invalid registry policy provided'

When we give the same policy using aws cli command, we are able to update the policy successfully.

aws ecr set-repository-policy --repository-name repo_name --policy-text file://policy.json

What is the issue when we update using boto3 sdk and how to fix them?

Asked By: Nandha

||

Answers:

I should have used set_repository_policy function for setting repository policy.

import json
conv_policy_text = json.dumps(policy_json)
client.set_repository_policy(repositoryName=CURRENT_ECR_NAME, policyText=conv_policy_text)
Answered By: Nandha