How can I tell if I'm logged in to a private Docker registry from a script?

后端 未结 7 1098
粉色の甜心
粉色の甜心 2021-02-04 23:59

How can I tell whether or not I\'m logged in to a private Docker registry server from a script? In other words, has docker login some.registry.com been run success

7条回答
  •  后悔当初
    2021-02-05 00:29

    I believe the error message will vary by registry implementation. However, my own technique is to pull an image that doesn't exist and parse any error message:

    $!/bin/sh
    repo="$1"
    msg=$(docker pull ${repo}/missing:missing 2>&1)
    case "$msg" in
      *"requested access to the resource is denied"*|*"pull access denied"*)
        echo "Logged out";;
      *"manifest unknown"*|*"not found"*)
        echo "Logged in, or read access for anonymous allowed";;
      *"Pulling from"*)
        echo "Missing image was not so missing after all?";;
      *) 
        echo "Unknown message: $msg";;
    esac
    

    This has been tested with the docker standalone registry and docker_auth. You'll want to test with registries that you may encounter.

    If your registry server allows anonymous pulls and you want to verify a push is possible, you can create a dummy empty image and replace the pull with a push of that image. E.g.

    #!/bin/sh
    repo=$1
    # note, I do not like the "." here, better to change it to an empty directory
    # see "mktemp" for an option if you cannot make your own empty directory somewhere
    docker build -t "${repo}/empty:test" -f - . <&1)
    rc=$?
    if [ "$rc" = "0" ]; then
      echo "Access granted to push"
    else
      case "$msg" in
        *"requested access to the resource is denied"*)
          echo "Access denied";;
        *) 
          echo "Unknown error message: $msg";;
      esac
    fi
    

提交回复
热议问题