Cross account ECR push with Jenkins

Cross account ECR push with Jenkins

ยท

4 min read

One of my favorite moments is when I solve something faster than my team lead. This was the first, and I work hard to be more moments like this.

So, the scenario is the following:

Untitled Diagram.png

Our Jenkins role has the following policies:

policies-edited.jpg

We will gonna take a look at our two managed policies, admin-assume and cross-account-push.

Admin-assume contains the following:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::<target-account-number>:role/r_aws-admin"
        }
    ]
}

With this, we can assume the role, called r_aws-admin in the other account.

Admin accounts usually able to perform every action in AWS, so its recommended to create a role with minimal permission, and assume just that.

And here is the cross-account-push policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowCrossAccountPush",
            "Effect": "Allow",
            "Action": [
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchCheckLayerAvailability",
                "ecr:PutImage",
                "ecr:InitiateLayerUpload",
                "ecr:UploadLayerPart",
                "ecr:CompleteLayerUpload"
            ],
            "Resource": "arn:aws:ecr:<account-b-region>:<account-b-number>:repository/<account-b-ecr-repository-name>"
        }
    ]
}

This policy enables every action on the target ECR repository, in account B.

This is only half of the story, we need to configure the other side too. ๐Ÿง

Firstly, in account B, we need to find r_aws-admin and add a trust relationship to it.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::<account-a-number>:root",
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

This will enable to use of assumeRole from account A to account B.

And then, the final step is to configure our ECR repository, to enable all operations from account A. You can find this on the toolbar when you click on your repository. Here is the policy:

{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "jenkins-policy",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::<account-a-number>:root",
          "arn:aws:iam::<account-b-number>:role/r_aws-admin"
        ]
      },
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:CompleteLayerUpload",
        "ecr:GetDownloadUrlForLayer",
        "ecr:InitiateLayerUpload",
        "ecr:ListImages",
        "ecr:PutImage",
        "ecr:UploadLayerPart"
      ]
    }
  ]
}

And that's it! Feel free to ask any questions, and happy learning! ๐Ÿ˜„