如何 运行 Docker 检查以获取 ECR 注册表中图像的图像元数据

How to run Docker inspect to obtain image meta-data of an image in the ECR registry

我拥有 ECR 注册表的相关访问权限,但是我无法通过 运行 Docker 检查命令获取图像元数据。我正在尝试

docker inspect ecrregistryurl/dockerimage:imageversion

如果不下载图像,您将无法获得有关图像的信息。您需要先拉取图像,然后进行检查

没有相同的命令。但是可能有 api 可用。对于 dockerhub,类似下面的东西有效

curl \
    --silent \
    --header "Accept: application/vnd.docker.distribution.manifest.v2+json" \
    "http://$REGISTRY_ADDRESS/v2/$image/manifests/$tag" |
    jq -r '.config.digest'

详情请见下文

https://hackernoon.com/inspecting-docker-images-without-pulling-them-4de53d34a604

更新

如@Ta运行 所述,我试过了,但它没有给我与 docker 检查相同的输出。这是文档中的 link。 https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries.html#registry_auth_http

#!/bin/bash
TOKEN=$(aws ecr get-authorization-token --output text --query authorizationData[].authorizationToken)
curl -i -H "Authorization: Basic $TOKEN" https://account_id.dkr.ecr.us-west-2.amazonaws.com/v2/redis/manifests/latest 

但检查输出与 docker 检查不同。

Docker inspect image_name

此命令只会检查您的本地图像,而不是您的注册表。

如何才能仅获取提供 ECR 的相关元数据。

aws ecr list-images --repository-name redis

它会给你一个图像标签和图像 ID。

aws ecr describe-images --repository-name redis

这将在名为 redis 的 repo 中提供所有图像和更多详细信息。

Now, For docker inspect first pull that images.

aws ecr get-login --no-include-email

运行 这个命令的输出。您将使用令牌登录。

docker pull account_id.dkr.ecr.us-west-2.amazonaws.com/redis:latest

然后 运行

docker pull account_id.dkr.ecr.us-west-2.amazonaws.com/redis:latest

你会得到你想要的。

或者,如果您已经 运行 在某个 ec2 实例上安装此图像,那么在该 ec2 实例上 运行 您将获得所需的结果。

docker inspect account_id.dkr.ecr.us-west-2.amazonaws.com/redis:latest

https://docs.aws.amazon.com/cli/latest/reference/ecr/index.html

是的,这是可行的。不过,您必须直接与注册表联系 API。

虽然 pull-then-inspect 方法在短期内可能会更慢且效率更低,但它使用比注册表更稳定的接口 API 因此长期坚持使用 pull 可能更易于维护-然后-检查。

import argparse
import json
import re
from pathlib import Path

import requests


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('image')
    args = parser.parse_args()

    # TODO: this is quick and dirty, check what the actual requirements are. In
    # particular, can image contain /, or tag contain :, maybe with escapes?
    RE_DOCKER_VERSION = re.compile(r"(?P<host>[^/]+)/(?P<image>[^:]+):(?P<tag>[^:]*)")

    if (match := RE_DOCKER_VERSION.fullmatch(args.image)) is None:
        raise Exception(f"Couldn’t parse {args.image}")

    host, image, tag = match["host"], match["image"], match["tag"]

    # If you are definitely using AWS ECR, you should use boto3 to get the login
    # password directly. But this should work for any registry requiring auth,
    # not just for ECR.
    docker_config = json.loads(Path("~/.docker/config.json").expanduser().read_text())
    # If you b64decode the following value, you will see for ECR it is `AWS:xxxx…`
    auth = docker_config["auths"][host]["auth"]

    response = requests.get(
        f"https://{host}/v2/{image}/manifests/{tag}",
        headers={
            "Authorization": f"Basic {auth}",
            # https://docs.docker.com/registry/spec/api/#pulling-an-image says we
            # need to pass this, though ECR seems to ignore it.
            # https://docs.docker.com/registry/spec/manifest-v2-2/ is supposed to
            # document the various manifest specs but I found it confusing.
            "Accept": "application/vnd.docker.distribution.manifest.v2+json"
        },
    )
    print('request 1 headers', response.headers)
    response.raise_for_status()
    print(response.text)
    manifest = response.json()
    digest = manifest["config"]["digest"]

    response = requests.get(
        f"https://{host}/v2/{image}/blobs/{digest}",
        headers={"Authorization": f"Basic {auth}"},
    )
    print('request 2 headers', response.headers)
    response.raise_for_status()
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))

if __name__ == "__main__":
    main()

对我来说,运行

python script.py 503014274146.dkr.ecr.us-east-1.amazonaws.com/foo:latest

打印

request 1 headers {'Content-Type': 'application/vnd.docker.distribution.manifest.v2+json', 'Docker-Distribution-Api-Version': 'registry/2.0', 'Sizes': '', 'Content-Length': '1329'}
{
   "schemaVersion": 2,
   "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
   "config": {
      "mediaType": "application/vnd.docker.container.image.v1+json",
      "size": 14512,
      "digest": "sha256:587ad9ba921cfa176f2e8fba84f7e78f1c38ef6ee147b5b2bd78ca46c66c973e"
   },
   "layers": [
      {
         "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
         "size": 2683875,
         "digest": "sha256:f2fd7513120f741931f5aa402fb8270465150e0bcd16e0b398a7cb394c2b8593"
      },
      ⋮
   ]
}

这是注册表中关于图像的信息。要是我们 检索配置 blob,我们将得到 docker inspect 报告的内容:

request 2 headers {'Last-Modified': 'Wed 24 Apr 2021 06:12:27 AM MDT', 'ETag': '"e5c907c0e39e44db69f5c361c8d46996-1"', 'x-amz-server-side-encryption': 'AES256', 'Accept-Ranges': 'bytes', 'Content-Type': 'application/octet-stream', 'Server': 'AmazonS3', 'Content-Length': '19351'}
{
  "architecture": "amd64",
  "config": {
    "Hostname": "",
    "Domainname": "",
    "User": "",
    "AttachStdin": false,
    "AttachStdout": false,
    "AttachStderr": false,
    "Tty": false,
    "OpenStdin": false,
    "StdinOnce": false,
    ⋮

还有很多我删掉的,比如环境变量 还有入口点和图层历史。