Search code examples
amazon-web-servicesamazon-ecr

AWS IAM user receive 401 when accessing to ECR repository, works with root user


I've started using AWS ECR to store my docker images. When I try to authenticate an IAM user, via Powershell (the same happens when I do via AWS command line) I receive a 401:UnAuthorized. If I use the Auth key/secret of the root user, it works and authenticates.

The PowerShell script I use is

(Get-ECRLoginCommand).Password | docker login --username AWS --password-stdin 474389077978.dkr.ecr.eu-west-3.amazonaws.com/myreoi

I've replaced the AWS user with the IAM user. I've also added the IAM user to the admins, but it doesn't seem enough.

Any suggestion? Thanks


Solution

  • The IAM user must be assigned a role to access the ECR service. This can be done by adding inline policy in the permission section of the groups.

    Please follow the below steps to perform use non-root IAM users can perform docker ecr operation.

    1.) Create IAM user say "ecr-user". 
    2.) Create IAM group called "ecr-group".
    3.) Add user ecr-user to ecr-group.
    4.) Create a role "ecr-role"
    5.) Attach the policy name "AmazonEC2ContainerServiceRole" to the role ecr-role.
    

    6.) Go in the group section of the AWS console.
    7.) Select the group "ecr-group" and go to the permission tab.
        Add policy - "AmazonEC2ContainerServiceRole" using attach policy button. 
    8.) "Click here" in the inline policy section of the permission tab.
    9.) Choose custom policy.
    10.) Choose a name for custom policy - "ecr-passon"
    11.) Add policy json given above - ensure to change your account id.
    
    {
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Action": [
            "iam:GetRole",
            "iam:PassRole"
        ],
        "Resource": "arn:aws:iam::<account-id>:role/ecr-role"
    }]}
    

    All these steps will attach the role ecr-role to the ecr-user of the group ecr-group with policy AmazonEC2ContainerServiceRole.

    AWS programmatic IAM users must assume a role to perform some operations.

    Use the reference to understand the pass on the role. Pass a Role to an AWS Service