使用 powershell 登录 azure 帐户而不弹出窗口

Cra*_*der 1 powershell azure azure-virtual-machine

我正在尝试使用 powershell 创建 Azure VM。我还有创建它的脚本。

首先我需要登录 Azure 帐户:

Login-AzureRMAccount
Run Code Online (Sandbox Code Playgroud)

这会弹出一个窗口来输入凭据。

其次我需要运行以下脚本:

$UserName = "username"
$Password = ConvertTo-SecureString "password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)    
New-AzureRmVm `
    -ResourceGroupName "RG1" `
    -Name "VM1" `
    -ImageName "Image1" `
    -Location "West US" `
    -Credential $psCred
Run Code Online (Sandbox Code Playgroud)

至此虚拟机创建成功。
但现在,我需要让这些脚本在有要求时自动运行。我面临的问题是,登录步骤会弹出一个窗口来输入我不想要的凭据。所以我尝试过类似的事情,但没有成功。

$username = "loginname@organization.com"
$SecurePassword = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)
Login-AzureRmAccount -Credential $cred 
Run Code Online (Sandbox Code Playgroud)

它给出的错误消息是:

Login-AzureRmAccount : accessing_ws_metadata_exchange_failed: Accessing WS metadata exchange failed: The underlying connection was closed: An unexpected error occurred on a send.
At line:4 char:1
+ Login-AzureRmAccount -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Connect-AzureRmAccount], AadAuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
Run Code Online (Sandbox Code Playgroud)

谁能告诉我这意味着什么以及如何纠正这个问题?谢谢!

Jay*_*ran 5

如果您计划使用 PowerShell 将任何服务自动化到 Azure 中,那么我建议使用服务主体而不是您自己的凭据连接 azure ,这将是一种安全的连接方式。

什么是服务主体?

Azure 服务主体是用户创建的应用程序、服务和自动化工具用来访问特定 Azure 资源的安全标识。将其视为具有特定角色和严格控制权限的“用户身份”(用户名和密码或证书)。与一般用户身份不同,它只需要能够执行特定的操作。如果您仅授予其执行管理任务所需的最低权限级别,则可以提高安全性。

按照本教程创建服务主体

我还在Microsoft 库中发布了一个示例 PowerShell 工作流程,用于创建服务主体,您也可以按照该流程操作。

创建服务主体后,您可以使用以下 PowerShell 命令登录 azure,无需任何弹出窗口

$applicationId = "<service prinicple application id>";
$securePassword = "<service prinicple password>" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-AzureRmAccount -ServicePrincipal -Credential $credential -TenantId "<your tenantid>"
Run Code Online (Sandbox Code Playgroud)

更新1:

由于某种原因/错误,上述内容将会失败。参考这个github问题

为了解决这个问题

在脚本前添加两行

Import-Module -Name AzureRM.Profile
Remove-AzureRmAccount
Run Code Online (Sandbox Code Playgroud)

更新2:

AzureRM 将不再接收新的 cmdlet 或功能。不过,AzureRM 模块仍由官方维护,并将在 2020 年 12 月之前修复错误。

您必须使用新的 Azure PowerShell Az 模块