Azure AD へサービス プリンシパル認証をさせるための簡単な PowerShell スクリプト
今回はほぼ自分の備忘録としての記載となるが、Azure ARM SDK 等のアプリケーションから Microsoft Azure のリソースを操作する場合は Azure リソース マネージャーでのサービス プリンシパルの認証 に記載されている内容を一通り租借をしなければならない。
上記の記事における「パスワードで認証する: PowerShell」については、以下の PowerShell スクリプトを利用することでサービスプリンシパル認証が可能な情報を取得できる。
# ログイン Login-AzureRmAccount # 利用するサブスクリプションを確認 Get-AzureRmSubscription # 利用するサブスクリプションを選択 $subscriptionId = 'your subscription id' Select-AzureRmSubscription -SubscriptionId $subscriptionId $displayName = 'your app name' $homePage = 'your home page url' $identifierUris = 'your identifier url' $password = 'your password' # Azure AD にアプリケーション オブジェクトを作成 $azureAdApplication = New-AzureRmADApplication -DisplayName $displayName -HomePage $homePage -IdentifierUris $identifierUris -Password $password # サービスプリンシパル オブジェクトを作成 New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId # サービス プリンシパル に権限を割り当て New-AzureRmRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName $azureAdApplication.ApplicationId # アプリで使えるようにするため、サービス プリンシパルとしてログインする $cred = Get-Credential # $azureAdApplication.ApplicationId/$password での認証情報を作成 $subscription = Get-AzureRmSubscription -SubscriptionId $subscriptionId Login-AzureRmAccount -Credential $cred -ServicePrincipal -TenantId $subscription.TenantId # 以下の 4つの情報があれば SDK 等のアプリで利用可能 ## subscription-id $subscription.SubscriptionId ## tenant-id $subscription.TenantId ## client-id $azureAdApplication.ApplicationId ## secret $password
上記の情報を利用して、Azure ARM SDK for Java で以下の様なコードが記述可能だ。
package org.mydomain.armsdksample; import java.util.List; import com.microsoft.azure.credentials.ApplicationTokenCredentials; import com.microsoft.azure.credentials.AzureEnvironment; import com.microsoft.azure.management.resources.ResourceManagementClient; import com.microsoft.azure.management.resources.ResourceManagementClientImpl; import com.microsoft.azure.management.resources.models.ResourceGroup; public class Main { final static String subscriptionId = "your subscription id"; final static String clientId = "your client id"; final static String tenantId = "your tenant id"; final static String secret = "your password"; public static void main(String[] args) throws Exception { ResourceManagementClient client = new ResourceManagementClientImpl( new ApplicationTokenCredentials(clientId, tenantId, secret, AzureEnvironment.AZURE)); client.setSubscriptionId(subscriptionId); List<ResourceGroup> rgList = client.getResourceGroupsOperations().list(null, null).getBody(); for (ResourceGroup rg : rgList) { System.out.println(rg.getId()); } System.out.println("end"); } }
備忘録に等しいが、ご参考までに。
参考
詳細な情報を知りたい場合は以下のリンクを参考にしてほしい。