Use AWS ECR Credential Helper with Multiple AWS Accounts
I have used AWS ECR with docker for years, A thing annoying me is I have to login every 24 hours to pull or push images since the access token expires in 24 hours. The good thing is we can use amazon-ecr-credential-helper to help us log in automatically. However, it is still not very helpful enough with multiple AWS Accounts, then I created a way to make it easier.
Install amazon-ecr-credential-helper
In case you haven’t used amazon-ecr-credential-helper before, I show you how to install it first.
NOTE: The download links of the pre-built execution files can be found on https://github.com/awslabs/amazon-ecr-credential-helper/releases. I used links of v0.4.0 in the gist that was the latest version when I wrote this article.
Two ways to pass AWS credentials
- Put credentials in
~/.aws/credentials
- Use
AWS_ACCESS_KEY_ID
andAWS_SECRET_ACCESS_KEY
environment variables
The user of the access key at least needs these permissions in order to pull and push images.
Add credHelper config into ~/.docker/config.json
, like
{
"credHelpers": {
"<account_id>.dkr.ecr.region.amazonaws.com": "ecr-login"
}
}
If you only have one AWS account that you are all good. Otherwise, you have to either use AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
or use AWS_PROFILE
environment variable to switch accounts every time.
Deal with Multiple Accounts
The idea is adding a proxy execution file for each account. The proxy file tells the helper what credential or profile to use based on ECR URL.
For UNIX-like users, you can use the below script and replace to your info to create the proxy file
NOTE: If you use vim or nano to add the script, you have to remove the \
escape to just$@
.
For windows users, you can create a docker-credential-ecr-login-<AWS_ACCOUNT_ID>.bat
file with the content below in a folder in PATH
@ECHO OFF# use either one method
## use credential
SET AWS_ACCESS_KEY_ID=<AWS_ACCESS_KEY_ID>
SET AWS_SECRET_ACCESS_KEY=<AWS_SECRET_ACCESS_KEY>## use profile
SET AWS_PROFILE=<AWS_PROFILE>docker-credential-ecr-login %*
Then update ~/.docker/docker.config
to like below, each ecr map each proxy file.
{
"credHelpers": {
"<account_id_1>.dkr.ecr.region.amazonaws.com": "ecr-login-<account_id_1>", "<account_id_2>.dkr.ecr.region.amazonaws.com": "ecr-login-<account_id_2>"
}
}
When you run docker pull or push <account_id>.dkr.ecr.region.amazonaws.com/<image_name>
, docker calls the proxy file and it calls the helper to get access token.
NOTE: the filename pattern of the helper is docker-credential-<value in config>
.
Now, we don’t need to log in or switch accounts anymore.