19

I see that ~/.dockercfg has your login credentials, but it is your email and not your username. I see that running docker login displays your username and prompts you to change it. But, you can you just get your username to put into a build script?

Bruno Bronosky
  • 66,273
  • 12
  • 162
  • 149

3 Answers3

16

Display the username with:

docker info | sed '/Username:/!d;s/.* //'

Store it in a variable with:

username=$(docker info | sed '/Username:/!d;s/.* //'); 
echo $username

Note that if you have bash history expansion (set +H) you will be unable to put double quotes around the command substitution (e.g. "$(cmd...)" because ! gets replaced with your last command. Escaping is very tricky with these nested expansions and using it unquoted as shown above is more readable and works.

Bruno Bronosky
  • 66,273
  • 12
  • 162
  • 149
Kevin Cantwell
  • 1,092
  • 14
  • 19
12

Update for modern Docker.

Seems that docker info no longer contains username. I have instead learned to extract it from the credential store via jq. I haven't tried this on every credStore, but for the ones I have checked on macOS and Linux, this works.

# line breaks added for readability; this also works as a oneliner
docker-credential-$(
  jq -r .credsStore ~/.docker/config.json
) list | jq -r '
  . |
    to_entries[] |
    select(
      .key | 
      contains("docker.io")
    ) |
    last(.value)
'

[bonus] Show the entire contents of your credential helper

In this case I've settled on docker-credential-desktop, but it should work with any. You can extract your credential helper from your Docker config as I did in the previous code block.

docker-credential-desktop list | \
    jq -r 'to_entries[].key'   | \
    while read; do
        docker-credential-desktop get <<<"$REPLY";
    done
Bruno Bronosky
  • 66,273
  • 12
  • 162
  • 149
  • 3
    Wow, I've just seen my Docker.io password in plain text – EternalLight May 23 '20 at 08:30
  • Hello! What do you mean by `modern Docker`? could you please specify a docker version number ? I am using docker 20.10.7 and the username is still printed with `docker info`. I would like to know if I need to prepare my scripts for future versions of docker or if we are using totally different software. Thanks! – djoproject Jun 12 '21 at 09:43
  • For PowerShell (Core Edition): `$credsStore = Get-Content "$env:USERPROFILE\.docker\config.json" | ConvertFrom-Json | Select-Object -ExpandProperty credsStore && $dockerUser = &"docker-credential-$credsStore.exe" list | ConvertFrom-Json -AsHashtable | Select-Object -ExpandProperty Values`. – Mavaddat Javid Jan 25 '22 at 18:54
0

This works to extract it, but technically it's a race condition.

username="$(sed 's/.*(//;s/).*//' <(docker login & sleep 1; kill %1))"

Surely there is something better.

Bruno Bronosky
  • 66,273
  • 12
  • 162
  • 149