Udalosti
Vytváranie aplikácií a agentov umelej inteligencie
17. 3., 21 - 21. 3., 10
Pripojte sa k sérii meetup a vytvorte škálovateľné riešenia AI na základe prípadov reálneho používania so spolupracovníkmi a odborníkmi.
Zaregistrovať saTento prehliadač už nie je podporovaný.
Inovujte na Microsoft Edge a využívajte najnovšie funkcie, aktualizácie zabezpečenia a technickú podporu.
Use this article to get started with the client library for Azure Container Registry. Follow these steps to try out example code for data-plane operations on images and artifacts.
Use the client library for Azure Container Registry to:
Azure Container Registry also has a management library for control-plane operations including registry creation and updates.
You need an Azure subscription and an Azure container registry to use this library.
To create a new Azure container registry, you can use the Azure portal, Azure PowerShell, or the Azure CLI. Here's an example using the Azure CLI:
az acr create --name MyContainerRegistry --resource-group MyResourceGroup \
--location westus --sku Basic
Push one or more container images to your registry. For steps, see Push your first image to your Azure container registry using the Docker CLI.
For more information, see About registries, repositories, and artifacts.
Source code | Package (NuGet) | API reference | Samples
To develop .NET application code that can connect to an Azure Container Registry instance, you will need the Azure.Containers.ContainerRegistry
library.
Install the Azure Container Registry client library for .NET with NuGet:
dotnet add package Azure.Containers.ContainerRegistry --prerelease
For your application to connect to your registry, you'll need to create a ContainerRegistryClient
that can authenticate with it. Use the Azure Identity library to add Microsoft Entra ID support for authenticating Azure SDK clients with their corresponding Azure services.
When you're developing and debugging your application locally, you can use your own user to authenticate with your registry. One way to accomplish this is to authenticate your user with the Azure CLI and run your application from this environment. If your application is using a client that has been constructed to authenticate with DefaultAzureCredential
, it will correctly authenticate with the registry at the specified endpoint.
// 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
});
See the Azure Identity README for more approaches to authenticating with DefaultAzureCredential
, both locally and in deployment environments. To connect to registries in non-public Azure clouds, see the API reference.
For more information on using Microsoft Entra ID with Azure Container Registry, see the authentication overview.
Each sample assumes there is a REGISTRY_ENDPOINT
environment variable set to a string containing the https://
prefix and the name of the login server, for example "https://myregistry.azurecr.io".
The following samples use asynchronous APIs that return a task. Synchronous APIs are also available.
Iterate through the collection of repositories in the registry.
// 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);
}
// 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);
}
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();
}
}
Source code | Package (Maven) | API reference | Samples
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-containers-containerregistry</artifactId>
<version>1.0.0-beta.3</version>
</dependency>
The Azure Identity library provides Microsoft Entra ID support for authentication.
The following samples assume you have a registry endpoint string containing the https://
prefix and the name of the login server, for example "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();
For more information on using Microsoft Entra ID with Azure Container Registry, see the authentication overview.
Each sample assumes there is a registry endpoint string containing the https://
prefix and the name of the login server, for example "https://myregistry.azurecr.io".
Iterate through the collection of repositories in the registry.
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
client.listRepositoryNames().forEach(repository -> System.out.println(repository));
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));
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();
});
}
Source code | Package (npm) | API reference | Samples
See our support policy for more details.
Install the Container Registry client library for JavaScript with npm
:
npm install @azure/container-registry
The Azure Identity library provides Microsoft Entra ID support for authentication.
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());
For more information on using Microsoft Entra ID with Azure Container Registry, see the authentication overview.
Each sample assumes there is a CONTAINER_REGISTRY_ENDPOINT
environment variable set to a string containing the https://
prefix and the name of the login server, for example "https://myregistry.azurecr.io".
Iterate through the collection of repositories in the registry.
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);
});
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);
});
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);
});
Source code | Package (Pypi) | API reference | Samples
Install the Azure Container Registry client library for Python with pip:
pip install --pre azure-containerregistry
The Azure Identity library provides Microsoft Entra ID support for authentication. The DefaultAzureCredential
assumes the AZURE_CLIENT_ID
, AZURE_TENANT_ID
, and AZURE_CLIENT_SECRET
environment variables are set. For more information, see Azure Identity environment variables.
# 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())
Each sample assumes there is a CONTAINERREGISTRY_ENDPOINT
environment variable set to a string containing the https://
prefix and the name of the login server, for example "https://myregistry.azurecr.io".
This sample assumes the registry has a repository 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")
This sample assumes the registry has a repository hello-world
with image tagged 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.
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]
Source code | Package (pkg.go.dev) | REST API reference
Install the Azure Container Registry client library for Go with go get
:
go get github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry
When you're developing and debugging your application locally, you can use azidentity.NewDefaultAzureCredential to authenticate. We recommend using a managed identity in a production environment.
import (
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)
func main() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
client, err := azcontainerregistry.NewClient("https://myregistry.azurecr.io", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
}
See the azidentity documentation for more information about other authentication approaches.
Each sample assumes the container registry endpoint URL is "https://myregistry.azurecr.io".
This sample assumes the registry has a repository hello-world
.
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)
func Example_listTagsWithAnonymousAccess() {
client, err := azcontainerregistry.NewClient("https://myregistry.azurecr.io", nil, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
ctx := context.Background()
pager := client.NewListTagsPager("library/hello-world", nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance page: %v", err)
}
for _, v := range page.Tags {
fmt.Printf("tag: %s\n", *v.Name)
}
}
}
This sample assumes the registry has a repository hello-world
with image tagged latest
.
package azcontainerregistry_test
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)
func Example_setArtifactProperties() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
client, err := azcontainerregistry.NewClient("https://myregistry.azurecr.io", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
ctx := context.Background()
res, err := client.UpdateTagProperties(ctx, "library/hello-world", "latest", &azcontainerregistry.ClientUpdateTagPropertiesOptions{
Value: &azcontainerregistry.TagWriteableProperties{
CanWrite: to.Ptr(false),
CanDelete: to.Ptr(false),
}})
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
fmt.Printf("repository library/hello-world - tag latest: 'CanWrite' property: %t, 'CanDelete' property: %t\n", *res.Tag.ChangeableAttributes.CanWrite, *res.Tag.ChangeableAttributes.CanDelete)
}
package azcontainerregistry_test
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry"
"log"
)
func Example_deleteImages() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
client, err := azcontainerregistry.NewClient("https://myregistry.azurecr.io", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
ctx := context.Background()
repositoryPager := client.NewListRepositoriesPager(nil)
for repositoryPager.More() {
repositoryPage, err := repositoryPager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance repository page: %v", err)
}
for _, r := range repositoryPage.Repositories.Names {
manifestPager := client.NewListManifestsPager(*r, &azcontainerregistry.ClientListManifestsOptions{
OrderBy: to.Ptr(azcontainerregistry.ArtifactManifestOrderByLastUpdatedOnDescending),
})
for manifestPager.More() {
manifestPage, err := manifestPager.NextPage(ctx)
if err != nil {
log.Fatalf("failed to advance manifest page: %v", err)
}
imagesToKeep := 3
for i, m := range manifestPage.Manifests.Attributes {
if i >= imagesToKeep {
for _, t := range m.Tags {
fmt.Printf("delete tag from image: %s", *t)
_, err := client.DeleteTag(ctx, *r, *t, nil)
if err != nil {
log.Fatalf("failed to delete tag: %v", err)
}
}
_, err := client.DeleteManifest(ctx, *r, *m.Digest, nil)
if err != nil {
log.Fatalf("failed to delete manifest: %v", err)
}
fmt.Printf("delete image with digest: %s", *m.Digest)
}
}
}
}
}
}
If you want to clean up and remove an Azure container registry, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.
In this quickstart, you learned about using the Azure Container Registry client library to perform operations on images and artifacts in your container registry.
For more information, see the API reference documentation:
Learn about the Azure Container Registry REST API.
Udalosti
Vytváranie aplikácií a agentov umelej inteligencie
17. 3., 21 - 21. 3., 10
Pripojte sa k sérii meetup a vytvorte škálovateľné riešenia AI na základe prípadov reálneho používania so spolupracovníkmi a odborníkmi.
Zaregistrovať saŠkolenie
Modul
Aprenda a crear y configurar una instancia de Azure Container Registry, el proceso de inserción de imágenes de contenedor en Azure Container Registry y explorar diferentes métodos de autenticación y características de seguridad para Azure Container Registry.
Dokumentácia
Inicio rápido: Creación de un registro en el portal - Azure Container Registry
Obtenga información rápidamente sobre cómo crear un registro de contenedor privado de Azure mediante Azure Portal, insertar una imagen de contenedor y extraer y ejecutar la imagen desde el registro.
Visualización de repositorios en Portal - Azure Container Registry
Use Azure Portal para ver los repositorios de Azure Container Registry, que hospedan imágenes de contenedor de Docker y otros artefactos compatibles.
Insertar y extraer imagen de contenedor mediante Azure Container Registry - Azure Container Registry
Inserte y extraiga imágenes de Docker en un registro de contenedor privado de Azure mediante la CLI de Docker.