Azure登陆的两种常见方式(user 和 service principal登陆)

通过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 会比较麻烦。

原文地址:https://www.cnblogs.com/yangwenbo214/p/9836138.html