快速入門:使用 Azure Container Registry 用戶端程式庫
使用此文章開始使用 Azure Container Registry 的用戶端程式庫。 請遵循下列步驟,在映像和成品上試用資料平面作業的範例程式碼。
使用 Azure Container Registry 的用戶端程式庫來:
- 列出登錄中的映像或成品
- 取得映像和成品、存放庫和標籤的中繼資料
- 在登錄項目上設定讀取/寫入/刪除屬性
- 刪除映像和成品、存放庫和標籤
Azure Container Registry 也有控制平面作業的管理程式庫,包括登錄建立和更新。
必要條件
您需要 Azure 訂用帳戶和 Azure 容器登錄,才能使用此程式庫。
若要建立新的 Azure 容器登錄,您可以使用 Azure 入口網站、Azure PowerShell 或 Azure CLI。 以下是使用 Azure CLI 的範例:
az acr create --name MyContainerRegistry --resource-group MyResourceGroup \ --location westus --sku Basic
將一或多個容器映像推送至您的登錄。 如需詳細步驟,請參閱使用 Docker CLI 推送您的第一個映像至 Azure 容器登錄庫。
重要概念
- Azure 容器登錄會儲存容器映像和 OCI 成品。
- 映像或成品是由資訊清單和圖層所組成。
- 資訊清單描述構成映像或成品的圖層。 透過其摘要唯一識別。
- 也可以標記映像或成品,以提供人類可讀取的別名。 映像或成品可以有零或多個與其相關聯的標籤,而且每個標籤可以唯一識別映像。
- 共用相同名稱但具有不同標籤的映像或成品集合是存放庫。
如需詳細資訊,請參閱關於登錄、存放庫和成品。
開始使用
原始程式碼 | 套件 (NuGet) | API 參考 | 範例
若要開發可連線到 Azure Container Registry 執行個體的 .NET 應用程式程式碼,您需要 Azure.Containers.ContainerRegistry
程式庫。
Install the package
使用 NuGet 安裝適用於 .NET 的 Azure Container Registry 用戶端程式庫:
dotnet add package Azure.Containers.ContainerRegistry --prerelease
驗證用戶端
若要讓應用程式連線到您的登錄,您必須建立 ContainerRegistryClient
,可以向其進行驗證。 使用 Azure 身分識別程式庫新增 Microsoft Entra ID 支援,以使用其對應的 Azure 服務來驗證 Azure SDK 用戶端。
當您在本機開發和偵錯應用程式時,您可以使用自己的使用者向登錄進行驗證。 完成此作業的其中一種方式是使用 Azure CLI 驗證使用者,並從此環境執行您的應用程式。 如果您的應用程式使用已建構的用戶端向 DefaultAzureCredential
進行驗證,會在指定的端點正確地向登錄進行驗證。
// 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
});
如需在本機和部署環境中向 DefaultAzureCredential
進行驗證的詳細資訊,請參閱 Azure 身分識別讀我檔案。 若要連線到非公用 Azure 雲端中的登錄,請參閱 API 參考。
如需有關搭配 Azure Container Registry 使用 Microsoft Entra ID 的詳細資訊,請參閱驗證概觀 (部分機器翻譯)。
範例
每個範例假設有一個 REGISTRY_ENDPOINT
環境變數設定為字串,其中包含 https://
前置詞和登入伺服器的名稱,例如「https://myregistry.azurecr.io"」。
下列範例會使用傳回工作的非同步 API。 您也可以使用同步 API。
以非同步方式列出存放庫
逐一查看登錄中的存放庫集合。
// 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();
}
}
開始使用
原始程式碼 | 套件 (Maven) | API 參考 | 範例
目前支援的環境
- Java 開發套件 (JDK) 第 8 版或更新版本。
包含套件
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-containers-containerregistry</artifactId>
<version>1.0.0-beta.3</version>
</dependency>
驗證用戶端
Azure 身分識別程式庫提供 Microsoft Entra ID 驗證支援。
下列範例假設您有一個登錄端點字串,其中包含 https://
前置詞和登入伺服器的名稱,例如「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 Container Registry 使用 Microsoft Entra ID 的詳細資訊,請參閱驗證概觀 (部分機器翻譯)。
範例
每個範例都假設有一個登錄端點字串,其中包含 https://
前置詞和登入伺服器的名稱,例如「https://myregistry.azurecr.io"」。
列出存放庫名稱
逐一查看登錄中的存放庫集合。
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();
});
}
開始使用
原始程式碼 | 套件 (npm) | API 參考 | 範例
目前支援的環境
如需詳細資訊,請參閱我們的支援原則。
安裝 @azure/container-registry
套件
使用 npm
安裝適用於 JavaScript 的 Container Registry 用戶端程式庫:
npm install @azure/container-registry
驗證用戶端
Azure 身分識別程式庫提供 Microsoft Entra ID 驗證支援。
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 Container Registry 使用 Microsoft Entra ID 的詳細資訊,請參閱驗證概觀 (部分機器翻譯)。
範例
每個範例假設有一個 CONTAINER_REGISTRY_ENDPOINT
環境變數設定為字串,其中包含 https://
前置詞和登入伺服器的名稱,例如「https://myregistry.azurecr.io"」。
以非同步方式列出存放庫
逐一查看登錄中的存放庫集合。
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);
});
開始使用
原始程式碼 | 套件 (Pypi) | API 參考 | 範例
Install the package
使用 pip 安裝適用於 Python 的 Azure Container Registry 用戶端程式庫:
pip install --pre azure-containerregistry
驗證用戶端
Azure 身分識別程式庫提供 Microsoft Entra ID 驗證支援。 DefaultAzureCredential
假設 AZURE_CLIENT_ID
、AZURE_TENANT_ID
和 AZURE_CLIENT_SECRET
環境變數已設定。 如需詳細資訊,請參閱 Azure 身分識別環境變數。
# 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())
範例
每個範例假設有一個 CONTAINERREGISTRY_ENDPOINT
環境變數設定為字串,其中包含 https://
前置詞和登入伺服器的名稱,例如「https://myregistry.azurecr.io"」。
以非同步方式列出標籤
此範例假設登錄具有存放庫 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")
以非同步方式設定成品屬性
此範例假設登錄具有存放庫 hello-world
,並且具有標記為 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]
開始使用
原始程式碼 | 封裝 (pkg.go.dev) | REST API 參考
Install the package
使用 go get
安裝適用於 Go 的 Azure Container Registry 用戶端程式庫:
go get github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry
驗證用戶端
當您在本機開發與偵錯應用程式時,您可以使用 azidentity.NewDefaultAzureCredential 進行驗證。 建議在實際執行環境中使用受控識別。
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)
}
}
如需其他驗證方法的詳細資訊,請參閱 azidentity 文件 (英文)。
範例
每個範例假設容器登錄端點 URL 為 "https://myregistry.azurecr.io"。
列出標籤
此範例假設登錄具有存放庫 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)
}
}
}
設定成品屬性
此範例假設登錄具有存放庫 hello-world
,並且具有標記為 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)
}
}
}
}
}
}
清除資源
如果您想要清除和移除 Azure 容器登錄,可以刪除資源或資源群組。 刪除資源群組也會刪除與其相關聯的任何其他資源。
下一步
在本快速入門中,您已了解如何使用 Azure Container Registry 用戶端程式庫,對容器登錄中的映像和成品執行作業。
如需詳細資訊,請參閱 API 參考文件:
了解 Azure Container Registry REST API。