Python 用Azure Container Registry クライアント ライブラリ - バージョン 1.2.0
Azure Container Registryを使用すると、コンテナー イメージと成果物を、すべての種類のコンテナー デプロイのプライベート レジストリに格納および管理できます。
Azure Container Registry のクライアント ライブラリを使用して、次のことを行います。
- レジストリ内のイメージまたは成果物を一覧表示する
- イメージと成果物、リポジトリ、タグのメタデータを取得する
- レジストリ項目の読み取り、書き込み、削除プロパティを設定する
- イメージと成果物、リポジトリ、タグを削除する
ソースコード | パッケージ (Pypi) | パッケージ (Conda) | API リファレンス ドキュメント | REST API のドキュメント | 製品ドキュメント
免責事項
Python 2.7 の Azure SDK Python パッケージのサポートは、2022 年 1 月 1 日に終了しました。 詳細と質問については、このパッケージを使用するには https://github.com/Azure/azure-sdk-for-python/issues/20691Python 3.7 以降が必要ですを参照してください。詳細については、「 Azure SDK for Python バージョンサポート ポリシー」を参照してください。
作業の開始
パッケージをインストールする
pip を使用して Python 用の Azure Container Registry クライアント ライブラリをインストールします。
pip install --pre azure-containerregistry
前提条件
- このパッケージを使用するには、Python 3.7 以降が必要です。
- このパッケージを使用するには、 Azure サブスクリプション と Container Registry アカウント が必要です。
新しい Container Registry を作成するには、Azure Portal、Azure PowerShell、または Azure CLI を使用できます。 Azure CLI を使う例を次に示します。
az acr create --name MyContainerRegistry --resource-group MyResourceGroup --location westus --sku Basic
クライアントを認証する
Azure Identity ライブラリでは、認証に対する Azure Active Directory のサポートが簡単に提供されます。 ではDefaultAzureCredential
、AZURE_CLIENT_ID
、AZURE_TENANT_ID
、および AZURE_CLIENT_SECRET
環境変数が設定されていることを前提としています。詳細については、「Azure Identity 環境変数」セクションを参照してください。
# Create a ContainerRegistryClient that will authenticate through Active Directory
from azure.containerregistry import ContainerRegistryClient
from azure.identity import DefaultAzureCredential
endpoint = "https://mycontainerregistry.azurecr.io"
audience = "https://management.azure.com"
client = ContainerRegistryClient(endpoint, DefaultAzureCredential(), audience=audience)
主要な概念
レジストリには、Docker イメージと OCI 成果物が格納されます。 イメージまたは成果物は、"マニフェスト"と "レイヤー" で構成されます。 イメージのマニフェストは、イメージを構成するレイヤーを記述し、 ダイジェストによって一意に識別されます。 画像に "タグ付け" して、人間が判読できるエイリアスを付けることもできます。 イメージまたは成果物には、0 個以上の タグ を関連付けることができ、各タグはイメージを一意に識別します。 同じ名前を共有し、異なるタグを持つイメージのコレクションは、 リポジトリと呼ばれます。
詳細については、「 コンテナー レジストリの概念」を参照してください。
例
次のセクションでは、次のような最も一般的な ACR サービス タスクをカバーするいくつかのコード スニペットを示します。
- レジストリ操作:
- BLOB とマニフェストの操作:
各サンプルでは、プレフィックスとログイン サーバーの名前 (例: "https://myregistry.azurecr.io") をhttps://
含む文字列に設定された環境変数があることをCONTAINERREGISTRY_ENDPOINT
前提としています。 匿名アクセスのサンプルは、環境変数CONTAINERREGISTRY_ANONREGISTRY_ENDPOINT
からエンドポイント値を取得しています。
リポジトリの一覧を表示する
レジストリ内のリポジトリのコレクションを反復処理します。
with ContainerRegistryClient(self.endpoint, self.credential) as client:
# Iterate through all the repositories
for repository_name in client.list_repository_names():
print(repository_name)
匿名アクセスを使用してタグを一覧表示する
匿名アクセスを使用して、リポジトリ内のタグのコレクションを反復処理します。
with ContainerRegistryClient(endpoint) as anon_client:
manifest = anon_client.get_manifest_properties("library/hello-world", "latest")
print(f"Tags of {manifest.repository_name}: ")
# Iterate through all the tags
for tag in manifest.tags:
print(tag)
成果物のプロパティを設定する
成果物のプロパティを設定します。
with ContainerRegistryClient(self.endpoint, self.credential) as client:
# Set permissions on image "library/hello-world:v1"
client.update_manifest_properties(
"library/hello-world",
"v1",
can_write=False,
can_delete=False
)
イメージを削除する
リポジトリ内の最初の 3 つより古いイメージを削除します。
with ContainerRegistryClient(self.endpoint, self.credential) as client:
for repository in client.list_repository_names():
# Keep the three most recent images, delete everything else
manifest_count = 0
for manifest in client.list_manifest_properties(
repository, order_by=ArtifactManifestOrder.LAST_UPDATED_ON_DESCENDING
):
manifest_count += 1
if manifest_count > 3:
# Make sure will have the permission to delete the manifest later
client.update_manifest_properties(
repository,
manifest.digest,
can_write=True,
can_delete=True
)
print(f"Deleting {repository}:{manifest.digest}")
client.delete_manifest(repository, manifest.digest)
画像のアップロード
完全なイメージをアップロードするには、個々のレイヤーと構成をアップロードする必要があります。 その後、イメージまたは成果物を記述するマニフェストをアップロードし、タグを割り当てることができます。
self.repository_name = "sample-oci-image"
layer = BytesIO(b"Sample layer")
config = BytesIO(json.dumps(
{
"sample config": "content",
}).encode())
with ContainerRegistryClient(self.endpoint, self.credential) as client:
# Upload a layer
layer_digest, layer_size = client.upload_blob(self.repository_name, layer)
print(f"Uploaded layer: digest - {layer_digest}, size - {layer_size}")
# Upload a config
config_digest, config_size = client.upload_blob(self.repository_name, config)
print(f"Uploaded config: digest - {config_digest}, size - {config_size}")
# Create an oci image with config and layer info
oci_manifest = {
"config": {
"mediaType": "application/vnd.oci.image.config.v1+json",
"digest": config_digest,
"sizeInBytes": config_size,
},
"schemaVersion": 2,
"layers": [
{
"mediaType": "application/vnd.oci.image.layer.v1.tar",
"digest": layer_digest,
"size": layer_size,
"annotations": {
"org.opencontainers.image.ref.name": "artifact.txt",
},
},
],
}
# Set the image with tag "latest"
manifest_digest = client.set_manifest(self.repository_name, oci_manifest, tag="latest")
print(f"Uploaded manifest: digest - {manifest_digest}")
画像をダウンロードする
完全なイメージをダウンロードするには、マニフェストをダウンロードし、個々のレイヤーと構成をダウンロードする必要があります。
with ContainerRegistryClient(self.endpoint, self.credential) as client:
# Get the image
get_manifest_result = client.get_manifest(self.repository_name, "latest")
received_manifest = get_manifest_result.manifest
print(f"Got manifest:\n{received_manifest}")
# Download and write out the layers
for layer in received_manifest["layers"]:
# Remove the "sha256:" prefix from digest
layer_file_name = layer["digest"].split(":")[1]
try:
stream = client.download_blob(self.repository_name, layer["digest"])
with open(layer_file_name, "wb") as layer_file:
for chunk in stream:
layer_file.write(chunk)
except DigestValidationError:
print(f"Downloaded layer digest value did not match. Deleting file {layer_file_name}.")
os.remove(layer_file_name)
print(f"Got layer: {layer_file_name}")
# Download and write out the config
config_file_name = "config.json"
try:
stream = client.download_blob(self.repository_name, received_manifest["config"]["digest"])
with open(config_file_name, "wb") as config_file:
for chunk in stream:
config_file.write(chunk)
except DigestValidationError:
print(f"Downloaded config digest value did not match. Deleting file {config_file_name}.")
os.remove(config_file_name)
print(f"Got config: {config_file_name}")
マニフェストの削除
with ContainerRegistryClient(self.endpoint, self.credential) as client:
get_manifest_result = client.get_manifest(self.repository_name, "latest")
# Delete the image
client.delete_manifest(self.repository_name, get_manifest_result.digest)
BLOB を削除する
with ContainerRegistryClient(self.endpoint, self.credential) as client:
get_manifest_result = client.get_manifest(self.repository_name, "latest")
received_manifest = get_manifest_result.manifest
# Delete the layers
for layer in received_manifest["layers"]:
client.delete_blob(self.repository_name, layer["digest"])
# Delete the config
client.delete_blob(self.repository_name, received_manifest["config"]["digest"])
トラブルシューティング
トラブルシューティングの詳細については、トラブルシューティング ガイドを参照してください。
全般
ACR クライアント ライブラリでは、 Azure Core で定義されている例外が発生します。
ログの記録
このライブラリでは、標準の ログ記録 ライブラリを使用してログを記録します。
HTTP セッション (URL、ヘッダーなど) に関する基本情報は、レベルで INFO
ログに記録されます。
要求/応答本文や未作成のヘッダーなど、詳細なDEBUG
レベルのログ記録は、クライアントで有効にすることも、キーワード (keyword)引数を使用してlogging_enable
操作ごとに有効にすることもできます。
SDK のログ記録に関する完全なドキュメントと例 については、こちらを参照してください。
オプションの構成
省略可能なキーワード (keyword)引数は、クライアントレベルと操作ごとのレベルで渡すことができます。 azure-core リファレンス ドキュメント では、再試行、ログ記録、トランスポート プロトコルなどの使用可能な構成について説明しています。
次の手順
- azure.containerregistry と サンプルを参照してください。
- デモや詳細なビデオをご覧ください。
- Azure Container Registry サービスの詳細を参照してください。
共同作成
このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、「 cla.microsoft.com」を参照してください。
このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。
Azure SDK for Python