Search code examples
aws-cloudformationamazon-ecr

How to define a Cloudformation ECR RepositoryPolicyText that can be referenced by other ECR repository definitions?


I was trying to create a RepositoryPolicyText which can be referenced by other ecr repositories defined in the cloudformation template. Something like this:

MyRepository: 
  Type: AWS::ECR::Repository
  Properties: 
    RepositoryName: "test-repository"
    RepositoryPolicyText: !Ref MyRepositoryPolicy

I tried to put in a managed policy, but it don't allow to create principal in there.

Is there any other way I can get the RepositoryPolicyText to work by reference?

Instead of replicating the RepositoryPolicyText, I can write once and reference in other repository definitions.


Solution

  • You can use a CloudFormation parameter with a default string, then this parameter can be shared across resources.

    Parameters:
      repoPolicy:
        Type: String
        Default: '{"Statement":[ {"Sid" : "a", "Effect" : "Allow", "Principal" : "*", "Action" : "ecr:*" } ]}'
    Resources:
      repoA:
        Type: 'AWS::ECR::Repository'
        Properties:
          RepositoryName: cfnrepoa
          RepositoryPolicyText: !Ref repoPolicy
      repoB:
        Type: 'AWS::ECR::Repository'
        Properties:
          RepositoryName: cfnrepob
          RepositoryPolicyText: !Ref repoPolicy