Search code examples
bashdockeramazon-ecr

Pushing docker image to aws ecr and bash scripting


I am trying to push an image to aws ecr in one line, so no manual intervention. I thought this worked but didn't tonight. I thought this took the output from the first command and executed it as a command in its own right then when finished executes the third command.

aws ecr get-login --no-include-email --region us-west-2 | bash | docker push XXYYXXYYXXYY.dkr.ecr.us-west-2.amazonaws.com/test-sns-stack

The output from the first command is of this form:

docker login -u AWS -p eyJwYXlsb2FkIjoicldnSWpITlpFZGhWQW1BdG1hcDB4SmYxYm9QbllTL0ZrVi9USWx0cTlnVUxtc1dpOVFVeW1MT2RLNy9tZmZCZ2l0SW9WRFBSRG1EWmxLYWozOGVwRXJqMy9TTW5oQUwxVWVBSHUrZFZCcEN0ZU1wTnVoVmdaa3BjQm14aWszTWRw....

When I manually run aws ecr login..., docker login -u .... docker push... We are good.

But running a one liner it is obviously failing to log in. Looks to me (!) as if it is not waiting until the command executes.

Bash not my strong point.


Solution

  • The documentation warns about using get-login:

    When you execute this docker login command, the command string can be visible to other users on your system in a process list (ps -e) display. Because the docker login command contains authentication credentials, there is a risk that other users on your system could view them this way. They could use the credentials to gain push and pull access to your repositories. If you are not on a secure system, you should use the ecr get-login-password command as described above.

    The best practice would be to use get-login-password as the same documentation says:

    aws ecr get-login-password --region region | docker login --username AWS --password-stdin aws_account_id.dkr.ecr.region.amazonaws.com
    

    Now, the docker push command that you want to execute will only make sense if the login was successful. This can be achieved using the && operator. The complete line, using your example, would be:

    aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin XXYYXXYYXXYY.dkr.ecr.us-west-2.amazonaws.com && docker push XXYYXXYYXXYY.dkr.ecr.us-west-2.amazonaws.com/test-sns-stack
    

    You can read more about the && operator and others in this answer.