Поделиться через


Azure Container Registry client library for JavaScript - version 1.1.2

Azure Container Registry позволяет хранить и управлять изображениями и артефактами контейнеров в приватном реестре для всех типов развертываний контейнеров.

Use the client library for Azure Container Registry to:

  • Перечислить изображения или артефакты в реестре.
  • Получите метаданные для изображений и артефактов, репозиториев и тегов
  • Задать свойства чтения, записи и удаления для элементов реестра.
  • Удалять изображения и артефакты, хранилища и теги

Ключевые ссылки:

Начало работы

Поддерживаемые в настоящее время среды

Подробнее смотрите нашу политику support для получения дополнительной информации.

Примечание: Этот пакет нельзя использовать в браузере из-за ограничений сервиса, пожалуйста, обратитесь к this document для получения рекомендаций.

Необходимые условия

Для создания нового Реестра контейнеров можно использовать Azure Portal, Azure PowerShell или Azure CLI. Вот пример с использованием Azure CLI:

az acr create --name MyContainerRegistry --resource-group MyResourceGroup --location westus --sku Basic

Установите пакет @azure/container-registry.

Установите клиентскую библиотеку Реестра контейнеров для JavaScript с помощью npm:

npm install @azure/container-registry

аутентификация клиента;

Библиотека идентификации Azure обеспечивает простую поддержку Azure Active Directory аутентификации.

import { ContainerRegistryClient, KnownContainerRegistryAudience } from "@azure/container-registry";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = "https://myregistryname.azurecr.io";
// Create a ContainerRegistryClient that will authenticate through Active Directory
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(), {
  audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
});

Обратите внимание, что эти примеры предполагают, что у вас установлена CONTAINER_REGISTRY_ENDPOINT переменная среды — URL, включая название сервера входа и префикс https:// .

Национальные облака

Для аутентификации в реестре в национальном облаке необходимо внести следующие дополнения в конфигурацию:

  • Задайте их authorityHost в настройках учетных данных или через AZURE_AUTHORITY_HOST переменную среды
  • Установите audience вход ContainerRegistryClientOptions
import { ContainerRegistryClient, KnownContainerRegistryAudience } from "@azure/container-registry";
import { DefaultAzureCredential, AzureAuthorityHosts } from "@azure/identity";

const endpoint = "https://myregistryname.azurecr.cn";
// Create a ContainerRegistryClient that will authenticate through AAD in the China national cloud
const client = new ContainerRegistryClient(
  endpoint,
  new DefaultAzureCredential({ authorityHost: AzureAuthorityHosts.AzureChina }),
  {
    audience: KnownContainerRegistryAudience.AzureResourceManagerChina,
  },
);

Для получения дополнительной информации об использовании AAD с Azure Container Registry, пожалуйста, ознакомьтесь с обзором Authentication Overview сервиса.

Основные понятия

Реестр хранит изображения Docker и артефакты OCI. Образ или артефакт состоит из манифеста и слоев. Манифест изображения описывает слои, из которых состоит изображение, и уникально идентифицируется по его дайджесу. Изображение также можно «отметить», чтобы придать ему псевдоним, читаемый человеком. Изображение или артефакт может иметь ноль или более тегов , и каждый тег уникально идентифицирует изображение. Коллекция изображений с одинаковым названием, но с разными тегами, называется репозиторием.

Для получения дополнительной информации, пожалуйста, см. раздел Container Registry Concepts.

Примеры

Операции реестра

Список репозиториев

Выполните итерацию по коллекции репозиториев в реестре.

import { ContainerRegistryClient, KnownContainerRegistryAudience } from "@azure/container-registry";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = "https://myregistryname.azurecr.io";
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(), {
  audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
});

const iterator = client.listRepositoryNames();
for await (const repository of iterator) {
  console.log(`  repository: ${repository}`);
}

Список тегов с анонимным доступом

import { ContainerRegistryClient, KnownContainerRegistryAudience } from "@azure/container-registry";

const endpoint = "https://myregistryname.azurecr.io";
// Create a new ContainerRegistryClient for anonymous access
const client = new ContainerRegistryClient(endpoint, {
  audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
});

// Obtain a RegistryArtifact object to get access to image operations
const image = client.getArtifact("library/hello-world", "latest");

// List the set of tags on the hello_world image tagged as "latest"
const tagIterator = image.listTagProperties();

// Iterate through the image's tags, listing the tagged alias for the image
console.log(`${image.fullyQualifiedReference}  has the following aliases:`);
for await (const tag of tagIterator) {
  console.log(`  ${tag.registryLoginServer}/${tag.repositoryName}:${tag.name}`);
}

Задание свойств артефакта

import { ContainerRegistryClient, KnownContainerRegistryAudience } from "@azure/container-registry";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = "https://myregistryname.azurecr.io";
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(), {
  audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
});

const image = client.getArtifact("library/hello-world", "v1");

// Set permissions on the image's "latest" tag
await image.updateTagProperties("latest", { canWrite: false, canDelete: false });

Удаление изображений

import { ContainerRegistryClient, KnownContainerRegistryAudience } from "@azure/container-registry";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = "https://myregistryname.azurecr.io";
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(), {
  audience: KnownContainerRegistryAudience.AzureResourceManagerPublicCloud,
});

// Iterate through repositories
const repositoryNames = client.listRepositoryNames();
for await (const repositoryName of repositoryNames) {
  const repository = client.getRepository(repositoryName);
  // Obtain the images ordered from newest to oldest by passing the `order` option
  const imageManifests = repository.listManifestProperties({
    order: "LastUpdatedOnDescending",
  });
  const imagesToKeep = 3;
  let imageCount = 0;
  // Delete images older than the first three.
  for await (const manifest of imageManifests) {
    imageCount++;
    if (imageCount > imagesToKeep) {
      const image = repository.getArtifact(manifest.digest);
      console.log(`Deleting image with digest ${manifest.digest}`);
      console.log(`  Deleting the following tags from the image:`);
      for (const tagName of manifest.tags) {
        console.log(`    ${manifest.repositoryName}:${tagName}`);
        image.deleteTag(tagName);
      }
      await image.delete();
    }
  }
}

Операции с блоб и манифеста

Отправка изображений

import { ContainerRegistryContentClient } from "@azure/container-registry";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = "https://myregistryname.azurecr.io";
const repository = "library/hello-world";
const client = new ContainerRegistryContentClient(
  endpoint,
  repository,
  new DefaultAzureCredential(),
);

const config = Buffer.from("Sample config");
const { digest: configDigest, sizeInBytes: configSize } = await client.uploadBlob(config);

const layer = Buffer.from("Sample layer");
const { digest: layerDigest, sizeInBytes: layerSize } = await client.uploadBlob(layer);

const manifest = {
  schemaVersion: 2,
  config: {
    digest: configDigest,
    size: configSize,
    mediaType: "application/vnd.oci.image.config.v1+json",
  },
  layers: [
    {
      digest: layerDigest,
      size: layerSize,
      mediaType: "application/vnd.oci.image.layer.v1.tar",
    },
  ],
};

await client.setManifest(manifest, { tag: "demo" });

Скачать изображения

import {
  ContainerRegistryContentClient,
  KnownManifestMediaType,
  OciImageManifest,
} from "@azure/container-registry";
import { DefaultAzureCredential } from "@azure/identity";
import { writeFileSync, createWriteStream } from "node:fs";

const endpoint = "https://myregistryname.azurecr.io";
const repository = "library/hello-world";
const client = new ContainerRegistryContentClient(
  endpoint,
  repository,
  new DefaultAzureCredential(),
);

// Download the manifest to obtain the list of files in the image based on the tag
const result = await client.getManifest("demo");

if (result.mediaType !== KnownManifestMediaType.OciImageManifest) {
  throw new Error("Expected an OCI image manifest");
}

const manifest = result.manifest as OciImageManifest;

// Manifests of all media types have a buffer containing their content; this can be written to a file.
writeFileSync("manifest.json", result.content);

const configResult = await client.downloadBlob(manifest.config.digest);
const configFile = createWriteStream("config.json");
configResult.content.pipe(configFile);

const trimSha = (digest: string): string => {
  const index = digest.indexOf(":");
  return index === -1 ? digest : digest.substring(index);
};

// Download and write out the layers
for (const layer of manifest.layers) {
  const fileName = trimSha(layer.digest);
  const layerStream = createWriteStream(fileName);
  const downloadLayerResult = await client.downloadBlob(layer.digest);
  downloadLayerResult.content.pipe(layerStream);
}

Удалить манифест

import { ContainerRegistryContentClient } from "@azure/container-registry";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = "https://myregistryname.azurecr.io";
const repository = "library/hello-world";
const client = new ContainerRegistryContentClient(
  endpoint,
  repository,
  new DefaultAzureCredential(),
);

const downloadResult = await client.getManifest("latest");
await client.deleteManifest(downloadResult.digest);

Удалить блоб

import {
  ContainerRegistryContentClient,
  KnownManifestMediaType,
  OciImageManifest,
} from "@azure/container-registry";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = "https://myregistryname.azurecr.io";
const repository = "library/hello-world";
const client = new ContainerRegistryContentClient(
  endpoint,
  repository,
  new DefaultAzureCredential(),
);

const downloadResult = await client.getManifest("latest");

if (downloadResult.mediaType !== KnownManifestMediaType.OciImageManifest) {
  throw new Error("Expected an OCI image manifest");
}

for (const layer of (downloadResult.manifest as OciImageManifest).layers) {
  await client.deleteBlob(layer.digest);
}

Troubleshooting

Для получения информации о устранении неполадок обратитесь к руководству устранению неполадок.

Дальнейшие действия

Пожалуйста, ознакомьтесь с каталогом samples для подробных примеров, показывающих, как использовать клиентские библиотеки.

Contributing

Если вы хотите внести вклад в эту библиотеку, пожалуйста, ознакомьтесь с руководством contributing guide чтобы узнать больше о том, как создавать и тестировать код.