aws-cdkamazon-ecraws-organizations

CDK 2.x: How to grant accounts within an AWS Organization pull access on an AWS ECR repository?


I am looking for example code describing how to grant pull access to an ECR repository across accounts in various sub-units of a AWS Organization hierarchy. Ideally, I would like to allowlist an organization unit. If necessary, I could allowlist accounts individually.

So far, I have started with the following Typescript deployed to the accounting holding the ECR repository:


const ecr_access_user = new iam.User(
      this,
      "build-docker-access" + stageSuffix,
      {
        userName: "build-docker-access" + stageSuffix,
      }
    );
repository.grantPull(ecr_access_user)

Now, how do I set up a policy that will grant access within an AWS Organization unit?


Solution

  • Create a resource policy for the repository granting permissions to the OUs you want through OU matching condition keys.

    repository.addToResourcePolicy(
      new iam.PolicyStatement({
        principals: [new iam.AnyPrincipal()], // or specify specific accounts
        actions: ["ecr:*"], // modify as needed
        conditions: {
          "ForAnyValue:StringLike": {
            "aws:PrincipalOrgPaths": ["o-my-organization/*/ou-abc/*"], // modify as needed
          },
        },
      })
    );
    
    

    Whatever principal wants to pull from the repo will also need the ecr:GetAuthorizationToken permission granted separately (since this permission does not belong to any specific resource).