Skip to content
Advertisement

AWS CDK How to include principals in IAM policy?

Hi I am working on AWS CDK. I am trying to create resource based policy. Below is my cloud formation template.

MWSECRRepository:
    Type: AWS::ECR::Repository
    Properties:
      RepositoryName: "location/location-service"
      RepositoryPolicyText:
        Version: "2012-10-17"
        Statement:
          - Sid: CurrentAccountPush
            Effect: Allow
            Principal:
              AWS:
                - 'arn:aws:iam::1234:root'  # dev
                - 'arn:aws:iam::1234:root'  # nonprod
                - 'arn:aws:iam::1234:root'  # prod
            Action:
              - 'ecr:GetDownloadUrlForLayer'
              - 'ecr:PutImage'
              - 'ecr:InitiateLayerUpload'
              - 'ecr:UploadLayerPart'
              - 'ecr:CompleteLayerUpload'

Below I am trying to create same using CDK.

 ECRRepository = ecr.Repository(self, id = "ECR", repository_name = "location/location-service");
        ECRRepository.add_to_resource_policy(iam.PolicyStatement(
            effect=iam.Effect.ALLOW,
            actions=["ecr:GetDownloadUrlForLayer","ecr:PutImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload"],
            principals=["arn:aws:iam::123:root","arn:aws:iam::123:root","arn:aws:iam::123:root"]
        ));


        ECRRepository.add_to_resource_policy(iam.PolicyStatement(
            effect=iam.Effect.ALLOW,
            #principals=["arn:aws:iam::123:root","arn:aws:iam::123:root","arn:aws:iam::123:root"]
            actions=["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]
        ));

        ECRRepository.add_lifecycle_rule(description="Image retention",  max_image_count=100, rule_priority=1);

This results in below error

Error: Expected object reference, got “arn:aws:iam::123:root”

Can someone help me to write correct syntax using python? Any help would be appreciated. Thanks

Advertisement

Answer

principals needs to be a list of IPrincipal instead of strings

ECRRepository.add_to_resource_policy(iam.PolicyStatement(
            effect=iam.Effect.ALLOW,
            actions=["ecr:GetDownloadUrlForLayer","ecr:PutImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload"],
            principals=[iam.ArnPrincipal("aws:iam::1234:root")]
        ));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement