🌊

Azure Container RegistryにManaged IDでアクセスする

に公開

概要

JAZUG Sapporoで Azure Container Apps についての発表したとき、以下の反応がありました。
気になったので Azure Container Registry(以下 ACR) にManaged IDでアクセスできるようにして、実際にAzure VMからACRのイメージをdocker pullできるか確認してみました。

https://x.com/web_se/status/1983264531825733738

Managed ID 自体の説明は記載しないので、以下を参照してください。
https://learn.microsoft.com/ja-jp/entra/identity/managed-identities-azure-resources/overview

Managed IDの設定

今回は動作確認として VM から ACR にManaged IDでアクセス(pull)してみます。
ACRとVMは既存のものを使います。

以下の流れで、Managed IDを作成・設定します。
今回は Azure CLI で実施します。

  1. Managed IDを作成
  2. Managed IDにACRへのアクセス権を付与
  3. Managed IDをVMに割り当て

以下の手順を参考にしています。

https://learn.microsoft.com/ja-jp/azure/container-registry/container-registry-authentication-managed-identity?tabs=azure-cli

1. Managed IDを作成

以下のコマンドラインを実行して、Managed IDを作成します。

az identity create --resource-group myResourceGroup --name myACRId

以下の2点は環境に合わせて変更します。

  • myResourceGroup: Managed IDを作成するリソースグループ
  • myARCId: Managed IDの名前

作成後は、後の手順で使うためidとprincipalIdの値を取得しておきます。

userID=$(az identity show --resource-group myResourceGroup --name myACRId --query id --output tsv)
spID=$(az identity show --resource-group myResourceGroup --name myACRId --query principalId --output tsv)

echoで変数を表示すると、以下のような形式の値が出ます。

echo $userID
/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myACRId
echo $spID
yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy

2. Managed IDにACRへのアクセス権を付与

アクセス権の付与する時に使うので、ACRのIDを取得しておきます。

resourceID=$(az acr show --resource-group myResourceGroup --name myContainerRegistry --query id --output tsv)

以下のコマンドラインで ACR への Pull を許可するアクセス権を付与します。

az role assignment create --assignee $spID --scope $resourceID --role "AcrPull"

3. Managed IDをVMに割り当て

以下のコマンドラインでManaged IDをVMに割り当てます。
今回は既存のVMを使用しています。

az vm identity assign --resource-group myResourceGroup --name myDockerVM --identities $userID

動作確認

Azure VM でdocker pullを実行し、ACRのイメージを pull してみます。
<xxxxxx>のところはACRの名前が入ります。
dev/backend:v0は私の環境にあるイメージです。

azureuser@dockerVM:~$ sudo az login --identity --client-id xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
azureuser@dockerVM:~$ sudo az acr login --name <xxxxxx>
Login Succeeded
azureuser@dockerVM:~$ sudo docker pull <xxxxxx>.azurecr.io/dev/backend:v0
v0: Pulling from dev/backend
ded5d587370b: Pull complete
07d1b5af933d: Pull complete
1eb98adba0eb: Pull complete
b617a119f8a2: Pull complete
beaa49fa38f1: Pull complete
8566b36070c1: Pull complete
b0b06581a769: Pull complete
4c9da6ff3a1f: Pull complete
57c30a9f6077: Pull complete
24f1a4f60d4a: Pull complete
Digest: sha256:f0bd4fb32667c58b4bbd94d7c006513d8888b4141628b29d5a85580899da11f4
Status: Downloaded newer image for <xxxxxx>.azurecr.io/dev/backend:v0

dev/backend:v0 を pull することができました。

まとめ

Managed IDを使うことで、認証情報をコードや設定に埋め込まずに安全にACRへアクセスできます。
今回はVMからのdocker pullで確認しましたが、Container AppsやFunctionsなど他のサービスでも同様に利用可能です。
アクセス権をまとめて管理でき、運用負荷の軽減にもつながるため、便利だと思いました。
今後はCI/CDなどにも活用していきたいと思います。

Discussion