Rychlý Start: použití klientských knihoven Azure Container Registry
Pomocí tohoto článku můžete začít s klientskou knihovnou pro Azure Container Registry. Pomocí těchto kroků můžete vyzkoušet ukázkový kód pro operace s datovou rovinou na obrázcích a artefaktech.
Pomocí klientské knihovny Azure Container Registry:
- Výpis obrázků nebo artefaktů v registru
- Získání metadat pro image a artefakty, úložiště a značky
- Nastavení vlastností čtení, zápisu a odstranění položek registru
- Odstranění imagí a artefaktů, úložišť a značek
Azure Container Registry má také knihovnu pro správu pro operace řízení roviny, včetně vytváření a aktualizace registru.
Požadavky
K použití této knihovny potřebujete předplatné Azure a službu Azure Container Registry.
pokud chcete vytvořit nový azure container registry, můžete použít Azure Portal, Azure PowerShellnebo rozhraní příkazového řádku azure. Tady je příklad použití Azure CLI:
az acr create --name MyContainerRegistry --resource-group MyResourceGroup \ --location westus --sku BasicNahrajte do registru jednu nebo víc imagí kontejneru. Postup najdete v tématu nahrání první image do služby Azure Container Registry pomocí rozhraní příkazového řádku Docker CLI.
Klíčové koncepty
- Registr kontejnerů Azure ukládá Image kontejnerů a artefakty OCI.
- Obrázek nebo artefakt se skládá z manifestu a vrstev.
- Manifest popisuje vrstvy, které tvoří obrázek nebo artefakt. Je jednoznačně identifikovaný jeho hodnotou Digest.
- Je také možné označit obrázek nebo artefakt tak , aby mu přidala uživatelsky čitelný alias. K obrázku nebo artefaktu může být přidružena nula nebo více značek a každá značka jednoznačně identifikuje obrázek.
- Kolekce imagí nebo artefaktů, které mají stejný název, ale mají jiné značky, je úložiště.
Další informace najdete v tématu o registrech, úložištích a artefaktech.
Začínáme
Zdrojový kód | | ukázky referencí k rozhraní API | balíčku (NuGet)
Pro vývoj kódu aplikace .NET, který se může připojit k instanci Azure Container Registry, budete potřebovat Azure.Containers.ContainerRegistry knihovnu.
Instalace balíčku
Instalace klientské knihovny Azure Container Registry pro .NET s NuGet:
dotnet add package Azure.Containers.ContainerRegistry --prerelease
Ověření klienta
Aby se vaše aplikace mohla připojit k vašemu registru, budete muset vytvořit ContainerRegistryClient , který se s ním může ověřit. pomocí knihovny identit azure můžete přidat podporu Azure Active Directory pro ověřování klientů azure SDK s odpovídajícími službami azure.
Při vývoji a ladění aplikace v místním prostředí můžete k ověřování pomocí svého registru použít vlastního uživatele. Toho můžete dosáhnout tak, že ověříte uživatele pomocí Azure CLI a spustíte aplikaci z tohoto prostředí. Pokud vaše aplikace používá klienta, který byl vytvořen k ověřování pomocí DefaultAzureCredential , bude správně ověřen v registru v zadaném koncovém bodu.
// Create a ContainerRegistryClient that will authenticate to your registry through Azure Active Directory
Uri endpoint = new Uri("https://myregistry.azurecr.io");
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
Další přístupy k ověřování pomocí místních i v prostředí nasazení najdete v souboru Readme pro Azure identity DefaultAzureCredential . Informace o připojení k registrům v neveřejných cloudech Azure najdete v referenčních informacích k rozhraní API.
Další informace o používání služby Azure AD s Azure Container Registry najdete v tématu Přehled ověřování.
Příklady
Každá ukázka předpokládá, že je REGISTRY_ENDPOINT Proměnná prostředí nastavena na řetězec obsahující https:// předponu a název přihlašovacího serveru, například " https://myregistry.azurecr.io ".
Následující ukázky používají asynchronní rozhraní API, která vrací úlohu. K dispozici jsou také synchronní rozhraní API.
Vypsat úložiště asynchronně
Iterujte pomocí kolekce úložišť v registru.
// Get the service endpoint from the environment
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("REGISTRY_ENDPOINT"));
// Create a new ContainerRegistryClient
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
// Get the collection of repository names from the registry
AsyncPageable<string> repositories = client.GetRepositoryNamesAsync();
await foreach (string repository in repositories)
{
Console.WriteLine(repository);
}
Nastavit vlastnosti artefaktu asynchronně
// Get the service endpoint from the environment
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("REGISTRY_ENDPOINT"));
// Create a new ContainerRegistryClient
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
// Get the collection of repository names from the registry
AsyncPageable<string> repositories = client.GetRepositoryNamesAsync();
await foreach (string repository in repositories)
{
Console.WriteLine(repository);
}
Asynchronní odstraňování imagí
using System.Linq;
using Azure.Containers.ContainerRegistry;
using Azure.Identity;
// Get the service endpoint from the environment
Uri endpoint = new Uri(Environment.GetEnvironmentVariable("REGISTRY_ENDPOINT"));
// Create a new ContainerRegistryClient
ContainerRegistryClient client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential(),
new ContainerRegistryClientOptions()
{
Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
});
// Iterate through repositories
AsyncPageable<string> repositoryNames = client.GetRepositoryNamesAsync();
await foreach (string repositoryName in repositoryNames)
{
ContainerRepository repository = client.GetRepository(repositoryName);
// Obtain the images ordered from newest to oldest
AsyncPageable<ArtifactManifestProperties> imageManifests =
repository.GetManifestPropertiesCollectionAsync(orderBy: ArtifactManifestOrderBy.LastUpdatedOnDescending);
// Delete images older than the first three.
await foreach (ArtifactManifestProperties imageManifest in imageManifests.Skip(3))
{
RegistryArtifact image = repository.GetArtifact(imageManifest.Digest);
Console.WriteLine($"Deleting image with digest {imageManifest.Digest}.");
Console.WriteLine($" Deleting the following tags from the image: ");
foreach (var tagName in imageManifest.Tags)
{
Console.WriteLine($" {imageManifest.RepositoryName}:{tagName}");
await image.DeleteTagAsync(tagName);
}
await image.DeleteAsync();
}
}
Začínáme
Zdrojový kód | Balíček (Maven) | Reference k rozhraní API | Ukázky
Aktuálně podporovaná prostředí
- Java Development Kit (JDK), verze 8 nebo novější.
Zahrnout balíček
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-containers-containerregistry</artifactId>
<version>1.0.0-beta.3</version>
</dependency>
Ověření klienta
knihovna identit Azure poskytuje Azure Active Directory podporu pro ověřování.
Následující ukázky předpokládají, že máte řetězec koncového bodu registru obsahující https:// předponu a název přihlašovacího serveru, například " https://myregistry.azurecr.io ".
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryAsyncClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildAsyncClient();
Další informace o používání služby Azure AD s Azure Container Registry najdete v tématu Přehled ověřování.
Příklady
Každá ukázka předpokládá, že existuje řetězec koncového bodu registru obsahující https:// předponu a název přihlašovacího serveru, například " https://myregistry.azurecr.io ".
Vypsat názvy úložišť
Iterujte pomocí kolekce úložišť v registru.
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
client.listRepositoryNames().forEach(repository -> System.out.println(repository));
Nastavit vlastnosti artefaktu
TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(defaultCredential)
.buildClient();
RegistryArtifact image = client.getArtifact(repositoryName, digest);
image.updateTagProperties(
tag,
new ArtifactTagProperties()
.setWriteEnabled(false)
.setDeleteEnabled(false));
Odstranění imagí
TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(defaultCredential)
.buildClient();
final int imagesCountToKeep = 3;
for (String repositoryName : client.listRepositoryNames()) {
final ContainerRepository repository = client.getRepository(repositoryName);
// Obtain the images ordered from newest to oldest
PagedIterable<ArtifactManifestProperties> imageManifests =
repository.listManifestProperties(
ArtifactManifestOrderBy.LAST_UPDATED_ON_DESCENDING,
Context.NONE);
imageManifests.stream().skip(imagesCountToKeep)
.forEach(imageManifest -> {
System.out.printf(String.format("Deleting image with digest %s.%n", imageManifest.getDigest()));
System.out.printf(" This image has the following tags: ");
for (String tagName : imageManifest.getTags()) {
System.out.printf(" %s:%s", imageManifest.getRepositoryName(), tagName);
}
repository.getArtifact(imageManifest.getDigest()).delete();
});
}
Začínáme
Zdrojový kód | Balíček (npm) | Reference k rozhraní API | Ukázky
Aktuálně podporovaná prostředí
Další podrobnosti najdete v našich zásadách podpory .
Nainstalujte balíček @azure/container-registry.
Nainstalujte klientskou knihovnu Container Registry pro JavaScript pomocí npm :
npm install @azure/container-registry
Ověření klienta
knihovna identit Azure poskytuje Azure Active Directory podporu pro ověřování.
const { ContainerRegistryClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT;
// Create a ContainerRegistryClient that will authenticate through Active Directory
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential());
Další informace o používání služby Azure AD s Azure Container Registry najdete v tématu Přehled ověřování.
Příklady
Každá ukázka předpokládá, že je CONTAINER_REGISTRY_ENDPOINT Proměnná prostředí nastavena na řetězec obsahující https:// předponu a název přihlašovacího serveru, například " https://myregistry.azurecr.io ".
Vypsat úložiště asynchronně
Iterujte pomocí kolekce úložišť v registru.
const { ContainerRegistryClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
async function main() {
// endpoint should be in the form of "https://myregistryname.azurecr.io"
// where "myregistryname" is the actual name of your registry
const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential());
console.log("Listing repositories");
const iterator = client.listRepositoryNames();
for await (const repository of iterator) {
console.log(` repository: ${repository}`);
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Nastavit vlastnosti artefaktu asynchronně
const { ContainerRegistryClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
async function main() {
// Get the service endpoint from the environment
const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";
// Create a new ContainerRegistryClient and RegistryArtifact to access image operations
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential());
const image = client.getArtifact("library/hello-world", "v1");
// Set permissions on the image's "latest" tag
await image.updateTagProperties("latest", { canWrite: false, canDelete: false });
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Asynchronní odstraňování imagí
const { ContainerRegistryClient } = require("@azure/container-registry");
const { DefaultAzureCredential } = require("@azure/identity");
async function main() {
// Get the service endpoint from the environment
const endpoint = process.env.CONTAINER_REGISTRY_ENDPOINT || "<endpoint>";
// Create a new ContainerRegistryClient
const client = new ContainerRegistryClient(endpoint, new DefaultAzureCredential());
// 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 `orderBy` option
const imageManifests = repository.listManifestProperties({
orderBy: "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();
}
}
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Začínáme
Zdrojový kód | Balíček (PyPi) | Reference k rozhraní API | Ukázky
Instalace balíčku
Instalace klientské knihovny Azure Container Registry pro Python s PIP:
pip install --pre azure-containerregistry
Ověření klienta
knihovna identit Azure poskytuje Azure Active Directory podporu pro ověřování. DefaultAzureCredentialPředpokládá, že AZURE_CLIENT_ID AZURE_TENANT_ID AZURE_CLIENT_SECRET jsou nastaveny proměnné prostředí, a. Další informace najdete v tématu proměnné prostředí Azure identity.
# Create a ContainerRegistryClient that will authenticate through Active Directory
from azure.containerregistry import ContainerRegistryClient
from azure.identity import DefaultAzureCredential
account_url = "https://mycontainerregistry.azurecr.io"
client = ContainerRegistryClient(account_url, DefaultAzureCredential())
Příklady
Každá ukázka předpokládá, že je CONTAINERREGISTRY_ENDPOINT Proměnná prostředí nastavena na řetězec obsahující https:// předponu a název přihlašovacího serveru, například " https://myregistry.azurecr.io ".
Vypsat značky asynchronně
Tato ukázka předpokládá, že registr obsahuje úložiště hello-world .
import asyncio
from dotenv import find_dotenv, load_dotenv
import os
from azure.containerregistry.aio import ContainerRegistryClient
from azure.identity.aio import DefaultAzureCredential
class ListTagsAsync(object):
def __init__(self):
load_dotenv(find_dotenv())
async def list_tags(self):
# Create a new ContainerRegistryClient
audience = "https://management.azure.com"
account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
credential = DefaultAzureCredential()
client = ContainerRegistryClient(account_url, credential, audience=audience)
manifest = await client.get_manifest_properties("library/hello-world", "latest")
print(manifest.repository_name + ": ")
for tag in manifest.tags:
print(tag + "\n")
Nastavit vlastnosti artefaktu asynchronně
Tato ukázka předpokládá, že registr obsahuje úložiště hello-world s příznakem image v1 .
import asyncio
from dotenv import find_dotenv, load_dotenv
import os
from azure.containerregistry.aio import ContainerRegistryClient
from azure.identity.aio import DefaultAzureCredential
class SetImagePropertiesAsync(object):
def __init__(self):
load_dotenv(find_dotenv())
async def set_image_properties(self):
# Create a new ContainerRegistryClient
account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
audience = "https://management.azure.com"
credential = DefaultAzureCredential()
client = ContainerRegistryClient(account_url, credential, audience=audience)
# [START update_manifest_properties]
# Set permissions on the v1 image's "latest" tag
await client.update_manifest_properties(
"library/hello-world",
"latest",
can_write=False,
can_delete=False
)
# [END update_manifest_properties]
# After this update, if someone were to push an update to "myacr.azurecr.io\hello-world:v1", it would fail.
# It's worth noting that if this image also had another tag, such as "latest", and that tag did not have
# permissions set to prevent reads or deletes, the image could still be overwritten. For example,
# if someone were to push an update to "myacr.azurecr.io\hello-world:latest"
# (which references the same image), it would succeed.
Asynchronní odstraňování imagí
import asyncio
from dotenv import find_dotenv, load_dotenv
import os
from azure.containerregistry import ManifestOrder
from azure.containerregistry.aio import ContainerRegistryClient
from azure.identity.aio import DefaultAzureCredential
class DeleteImagesAsync(object):
def __init__(self):
load_dotenv(find_dotenv())
async def delete_images(self):
# [START list_repository_names]
audience = "https://management.azure.com"
account_url = os.environ["CONTAINERREGISTRY_ENDPOINT"]
credential = DefaultAzureCredential()
client = ContainerRegistryClient(account_url, credential, audience=audience)
async with client:
async for repository in client.list_repository_names():
print(repository)
# [END list_repository_names]
# [START list_manifest_properties]
# Keep the three most recent images, delete everything else
manifest_count = 0
async for manifest in client.list_manifest_properties(repository, order_by=ManifestOrder.LAST_UPDATE_TIME_DESCENDING):
manifest_count += 1
if manifest_count > 3:
await client.delete_manifest(repository, manifest.digest)
# [END list_manifest_properties]
Vyčištění prostředků
Pokud chcete vyčistit a odebrat službu Azure Container Registry, můžete prostředek nebo skupinu prostředků odstranit. Odstraněním skupiny prostředků se odstraní také všechny další prostředky, které jsou k ní přidružené.
Další kroky
V tomto rychlém startu jste se dozvěděli o použití klientské knihovny Azure Container Registry k provádění operací s imagemi a artefakty ve vašem registru kontejneru.
Další informace najdete v referenční dokumentaci k rozhraní API:
Přečtěte si o REST APIAzure Container Registry.