Azure登錄的兩種常見方式(user 和 service principal登錄)

經過Powershell 登錄Azure(Azure MoonCake爲例)通常常見的有兩種方式

1. 用戶交互式登錄

前提條件:有一個AAD account
此種登錄方式會彈出一個登錄框,讓你輸入一個.onmschina.cn的帳號,而後根據選擇的訂閱操做相應的資源。shell

# set Azure Enviroment into China Mooncake.  
$EnvironmentName ="AzureChinaCloud" 
 
# Give your subcriptionID here.  
$SubscriptionId="*********" 
 
##login  
Login-AzureRmAccount -EnvironmentName 'AzureChinaCloud' 
Set-AzureRmContext -SubscriptionId $SubscriptionId

缺點:會彈出登錄框,讓你輸入帳號密碼進行登錄,不適合自動化場景。app

此處也能改爲隱氏登錄的。具體參考https://stackoverflow.com/questions/37249623/how-to-login-without-promptspa

Read-Host "Enter Password" -AsSecureString | ConvertTo-SecureString `
-AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Password.txt"
# The azure account here must not be a Live ID.
$username = "<your Azure account>"
$SecurePassword = Get-Content "C:\Password.txt" | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
     -argumentlist $username, $SecurePassword

Login-AzureRmAccount -Credential $cred -EnvironmentName 'AzureChinaCloud'

2. AAD Service Principal登錄 前提條件:

須要在Azure AD 中去註冊一個app(service principal),並拿到這個app的Appliaction和key。此處你須要爲app添加相應的權限。
運行完,直接根據選定的訂閱就能操做Azure 訂閱資源了。code

# the AAD app applicationID  
$ServicePrincipalApplicationId="9059226d-******" 
 
# AAD app key  
$ServicePrincipalPassword="********************" 
 
# the AAD directory ID = tenantID  
$TenantId= "*********************" 
 
# set Azure to Mooncake  
$EnvironmentName ="AzureChinaCloud" 
$SubscriptionId="*******************************" 
$spPassword =  ConvertTo-SecureString $ServicePrincipalPassword -AsPlainText -Force
  
$AzureServicePrincipalCreds = New-Object System.Management.Automation.PSCredential ($ServicePrincipalApplicationId, $spPassword)  
Add-AzureRmAccount -Credential $AzureServicePrincipalCreds -ServicePrincipal -TenantId $TenantId -Environment $EnvironmentName 
Set-AzureRmContext -SubscriptionId $SubscriptionId

缺點:泄露AAD app 的applicationID 和key 會比較麻煩。ip

相關文章
相關標籤/搜索