将 docker 图像推送到 aws ecr 和 bash 脚本

Pushing docker image to aws ecr and bash scripting

我试图在一行中将图像推送到 aws ecr,因此无需人工干预。我认为这有效但今晚没有。我认为这会获取第一个命令的输出并将其作为命令单独执行,然后在完成后执行第三个命令。

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

第一个命令的输出是这种形式:

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

当我手动 运行 aws ecr login..., docker login -u .... docker push... 我们很好

但是 运行显然登录失败。在我看来 (!) 好像它没有等到命令执行。

Bash不是我的强项

我认为这里的主要问题是围绕 bash | 的前提。实际上,通过管道传输的命令 运行 是并行的,这意味着它们同时开始,但不一定同时结束。

&& 替换最后一个管道可能会解决您的问题:

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 documentation 警告使用 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.

最佳做法是使用 get-login-password,正如 the same documentation 所说:

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

现在,您要执行的docker push命令只有在登录成功后才有意义。这可以使用 && 运算符来实现。使用您的示例,完整的行将是:

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

您可以在 this answer 中阅读有关 && 运算符和其他运算符的更多信息。