Hızlı Başlangıç: İstemci kitaplıklarını Azure Container Registry kullanma
Bu makaleyi kullanarak istemci kitaplığını kullanmaya Azure Container Registry. Görüntüler ve yapıtlar üzerinde veri düzlemi işlemleri için örnek kodu denemek için bu adımları izleyin.
İstemci kitaplığını kullanarak şunları Azure Container Registry:
- Kayıt defterindeki görüntüleri veya yapıtları listele
- Görüntüler ve yapıtlar, depolar ve etiketler için meta verileri alma
- Kayıt defteri öğeleri üzerinde okuma/yazma/silme özelliklerini ayarlama
- Görüntüleri ve yapıtları, depoları ve etiketleri silme
Azure Container Registry kayıt defteri oluşturma ve güncelleştirmeler de dahil olmak üzere denetim düzlemi işlemleri için bir yönetim kitaplığına da sahip olur.
Önkoşullar
Bu kitaplığı kullanmak için bir Azure aboneliğine ve Bir Azure kapsayıcı kayıt defterine ihtiyacınız vardır.
Yeni bir Azure kapsayıcı kayıt defteri oluşturmak için Azure portal , Azure PowerShellveya Azure CLI kullanabilirsiniz. Azure CLI'nin kullanımına bir örnek aşağıdaki gibidir:
az acr create --name MyContainerRegistry --resource-group MyResourceGroup \ --location westus --sku BasicKayıt defterinize bir veya daha fazla kapsayıcı görüntü itin. Adımlar için bkz. Docker CLI kullanarak ilk görüntülerinizi Azure kapsayıcı kayıt defterinize itme.
Önemli kavramlar
- Azure kapsayıcı kayıt defteri, kapsayıcı görüntülerini ve OCI yapıtlarını depolar.
- Görüntü veya yapıt bir bildirimden ve katmanlardan oluşur.
- Bildirim, görüntüyü veya yapıyı tanımlayan katmanları açıklar. Özetiyle benzersiz olarak tanımlanır.
- Bir görüntü veya yapıt, insan tarafından okunabilir bir diğer ad vermek için etiketlenebilir. Bir görüntü veya yapıtla ilişkilendirilmiş sıfır veya daha fazla etiket olabilir ve her etiket görüntüyü benzersiz olarak tanımlar.
- Aynı adı paylaştığı ancak farklı etiketleri olan görüntü veya yapıt koleksiyonu bir depodur.
Daha fazla bilgi için bkz. Kayıt defterleri, depolar ve yapıtlar hakkında.
başlarken
Kaynak kodu | Paket (NuGet) | API başvurusu | Örnekleri
Bir Azure Container Registry örneğine bağlanacak .NET uygulama kodu geliştirmek için kitaplığı Azure.Containers.ContainerRegistry gerekir.
Paketi yükleme
.NET için Azure Container Registry kitaplığını yükleme ve NuGet:
dotnet add package Azure.Containers.ContainerRegistry --prerelease
İstemcinin kimliğini doğrulama
Uygulamanın kayıt defterinize bağlanması için, bu kayıt defteriyle kimlik doğrulaması ContainerRegistryClient yapmak için bir oluşturmanız gerekir. Azure SDK istemcilerinin kimliklerini ilgili Azure Azure Active Directory kimlik doğrulama desteği eklemek için Azure Kimlik kitaplığını kullanın.
Yerel olarak uygulama geliştiriyor ve hata ayıklarken, kayıt defteriniz ile kimlik doğrulaması yapmak için kendi kullanıcınızı kullanabilirsiniz. Bunu gerçekleştirmenin bir yolu, azure CLI ile kullanıcı kimliğini doğrulamak ve bu ortamdan uygulama çalıştırmaktır. Uygulamanız ile kimlik doğrulaması yapmak için oluşturulmuş bir istemci kullanıyorsa, belirtilen uç noktada kayıt DefaultAzureCredential defteriyle doğru kimlik doğrulaması yapılacaktır.
// 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
});
ile kimlik doğrulamaya yönelik hem yerel hem de dağıtım ortamlarında daha fazla yaklaşım için bkz. Azure Identity DefaultAzureCredential README. Genel olmayan Azure bulutlarında kayıt defterlerine bağlanmak için API başvurusuna bakın.
Azure AD'nin Azure Container Registry kullanma hakkında daha fazla bilgi için bkz. kimlik doğrulamasına genel bakış.
Örnekler
Her örnek, ön eki ve oturum açma sunucusunun adını içeren bir dizeye ayarlanmış bir ortam değişkeni olduğunu REGISTRY_ENDPOINT https:// varsaymaktadır, örneğin " https://myregistry.azurecr.io ".
Aşağıdaki örneklerde bir görev dönüşen zaman uyumsuz API'ler 2. Zaman uyumlu API'ler de kullanılabilir.
Depoları zaman uyumsuz olarak listele
Kayıt defterindeki depo koleksiyonunun üzerinden geçerek.
// 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);
}
Yapıt özelliklerini zaman uyumsuz olarak ayarlama
// 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);
}
Görüntüleri zaman uyumsuz olarak silme
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();
}
}
başlarken
Kaynak kodu | Paket (Maven) | API başvurusu | Örnekleri
Şu anda desteklenen ortamlar
- Java Development Kit (JDK), sürüm 8 veya sonrası.
Paketi dahil etmek
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-containers-containerregistry</artifactId>
<version>1.0.0-beta.3</version>
</dependency>
İstemcinin kimliğini doğrulama
Azure Kimlik kitaplığı, kimlik doğrulaması Azure Active Directory destek sağlar.
Aşağıdaki örneklerde, ön eki ve oturum açma sunucusunun adını içeren bir kayıt defteri uç noktası dizeniz olduğu varsay https:// varsayabilirsiniz, örneğin " 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();
Azure AD'nin Azure Container Registry kullanma hakkında daha fazla bilgi için bkz. kimlik doğrulamasına genel bakış.
Örnekler
Her örnek, ön eki ve oturum açma sunucusunun adını içeren bir kayıt defteri uç noktası dizesi olduğunu https:// varsayıyor, örneğin " https://myregistry.azurecr.io ".
Depo adlarını listele
Kayıt defterindeki depo koleksiyonunun üzerinden geçerek.
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
ContainerRegistryClient client = new ContainerRegistryClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
client.listRepositoryNames().forEach(repository -> System.out.println(repository));
Yapıt özelliklerini ayarlama
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));
Görüntüleri silme
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();
});
}
başlarken
Kaynak kodu | Paket (npm) | API başvurusu | Örnekleri
Şu anda desteklenen ortamlar
Diğer ayrıntılar için destek ilkemize bakın.
@azure/container-registry paketini yükleyin
ile JavaScript Container Registry kitaplığını npm yükleyin:
npm install @azure/container-registry
İstemcinin kimliğini doğrulama
Azure Kimlik kitaplığı, kimlik doğrulaması Azure Active Directory destek sağlar.
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());
Azure AD'nin Azure Container Registry kullanma hakkında daha fazla bilgi için bkz. kimlik doğrulamasına genel bakış.
Örnekler
Her örnek, ön eki ve oturum açma sunucusunun adını içeren bir dizeye ayarlanmış bir ortam değişkeni olduğunu CONTAINER_REGISTRY_ENDPOINT https:// varsaymaktadır, örneğin " https://myregistry.azurecr.io ".
Depoları zaman uyumsuz olarak listele
Kayıt defterindeki depo koleksiyonunun üzerinden geçerek.
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);
});
Yapıt özelliklerini zaman uyumsuz olarak ayarlama
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);
});
Görüntüleri zaman uyumsuz olarak silme
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);
});
başlarken
Kaynak kodu | Paket (Pypi) | API başvurusu | Örnekleri
Paketi yükleme
Pip ile Python Azure Container Registry istemci kitaplığını yükleyin:
pip install --pre azure-containerregistry
İstemcinin kimliğini doğrulama
Azure Kimlik kitaplığı, kimlik doğrulaması Azure Active Directory destek sağlar. , DefaultAzureCredential ve ortam AZURE_CLIENT_ID AZURE_TENANT_ID değişkenlerinin ayar olduğunu AZURE_CLIENT_SECRET varsaymaktadır. Daha fazla bilgi için bkz. Azure Identity ortam değişkenleri.
# 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())
Örnekler
Her örnek, ön eki ve oturum açma sunucusunun adını içeren bir dizeye ayarlanmış bir ortam değişkeni olduğunu CONTAINERREGISTRY_ENDPOINT https:// varsaymaktadır, örneğin " https://myregistry.azurecr.io ".
Etiketleri zaman uyumsuz olarak listele
Bu örnek, kayıt defterinde bir deposu olduğunu hello-world varsayıyor.
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")
Yapıt özelliklerini zaman uyumsuz olarak ayarlama
Bu örnek, kayıt defterinde görüntü etiketli bir hello-world depo olduğunu v1 varsayıyor.
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.
Görüntüleri zaman uyumsuz olarak silme
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]
Kaynakları temizleme
Bir Azure kapsayıcı kayıt defterini temizlemek ve kaldırmak için kaynağı veya kaynak grubunu silebilirsiniz. Kaynak grubunun silinmesi, kaynak grubuyla ilişkilendirilmiş diğer tüm kaynakları da siler.
Sonraki adımlar
Bu hızlı başlangıçta, kapsayıcı kayıt defterinizin görüntüler ve yapıtlar üzerinde işlem gerçekleştirmek için Azure Container Registry istemci kitaplığını kullanmayı öğrendiniz.
Daha fazla bilgi için API başvurusu belgelerine bakın:
Azure Container Registry REST API.