通過Powershell 登陸Azure(Azure MoonCake為例)一般常見的有兩種方式
1. 用戶交互式登陸
前提條件:有一個AAD account
此種登陸方式會彈出一個登陸框,讓你輸入一個.onmschina.cn的賬號,然后根據選擇的訂閱操作相應的資源。
# set Azure Enviroment into China Mooncake.
$EnvironmentName ="AzureChinaCloud"
# Give your subcriptionID here.
$SubscriptionId="*********"
##login
Login-AzureRmAccount -EnvironmentName 'AzureChinaCloud'
Set-AzureRmContext -SubscriptionId $SubscriptionId
缺點:會彈出登陸框,讓你輸入賬號密碼進行登陸,不適合自動化場景。
此處也能改成隱氏登陸的。具體參考https://stackoverflow.com/questions/37249623/how-to-login-without-prompt
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 訂閱資源了。
# 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 會比較麻煩。