azure 使用Connect-AzAccount服务主体通过身份验证从dotnet内调用PowerShell脚本

neekobn8  于 2022-12-24  发布在  Shell
关注(0)|答案(1)|浏览(383)

使用dotnet7后台工作进程,调用PowerShell

using PowerShell ps = PowerShell.Create();
 ps.AddScript("auth.ps1"); 
 var pipelineObjects = await ps.InvokeAsync();

此处使用Az.Accounts版本2.2.3的PowerShell代码最少

Import-Module Az.Accounts
Clear-AzContext -Force 

$tenantID = " " 
$subscriptionID = " "

 $azureAplicationId = " ";
 $azurePassword = ConvertTo-SecureString "" -AsPlainText -Force; 
 $credentials = New-Object System.Management.Automation.PSCredential($azureAplicationId, $azurePassword);  

try 
{ 
     Connect-AzAccount -Credential $credentials -TenantId $tenantID -ServicePrincipal -ErrorAction Stop
}
catch 
{   
    Write-Error  $Exception ; 
}

例外的是

PSMessageDetails      :
Exception             : System.EntryPointNotFoundException: Entry point was not found.
                           at System.Threading.Tasks.Sources.IValueTaskSource`1.GetStatus(Int16 token)
                           at Microsoft.Azure.PowerShell.Authenticators.MsalAccessToken.GetAccessTokenAsync(String callerClassName, String parametersLog, TokenCredential tokenCredential, TokenRequestContext requestContext, CancellationToken cancellationToken, String tenantId, String userId, String homeAccountId)
                           at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.Authenticate(IAzureAccount account, IAzureEnvironment environment, String tenant, SecureString password, String promptBehavior, Action`1 promptAction, IAzureTokenCache tokenCache, String resourceId)
                           at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.AcquireAccessToken(IAzureAccount account, IAzureEnvironment environment, String tenantId, SecureString password, String promptBehavior, Action`1 promptAction, String resourceId)
                           at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.Login(IAzureAccount account, IAzureEnvironment environment, String tenantIdOrName, String subscriptionId, String subscriptionName, SecureString password, Boolean skipValidation, Action`1 promptAction, String name, Boolean shouldPopulateContextList, Int32 maxContextPopulation, String authScope)
                           at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass127_2.<ExecuteCmdlet>b__5()
                           at System.Threading.Tasks.Task`1.InnerInvoke()
                           at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
                        --- End of stack trace from previous location ---
                           at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
                           at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
                        --- End of stack trace from previous location ---
                           at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass127_0.<ExecuteCmdlet>b__1(AzureRmProfile localProfile, RMProfileClient profileClient, String name)
                           at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass136_0.<SetContextWithOverwritePrompt>b__0(AzureRmProfile prof, RMProfileClient client)
                           at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.ModifyContext(Action`2 contextAction)
                           at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.SetContextWithOverwritePrompt(Action`3 setContextAction)
                           at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.ExecuteCmdlet()
                           at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.<ExecuteSynchronouslyOrAsJob>b__3_0(T c)
                           at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
                           at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
                           at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
TargetObject          :
CategoryInfo          : CloseError: (:) [Connect-AzAccount], EntryPointNotFoundException
FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 15
PipelineIterationInfo : {}

MyCommand             : Connect-AzAccount
BoundParameters       : {}
UnboundArguments      : {}
ScriptLineNumber      : 15
OffsetInLine          : 6
HistoryId             : 1
ScriptName            :
Line                  :      Connect-AzAccount -Credential $credentials -TenantId $tenantID -ServicePrincipal -ErrorAction Stop

PositionMessage       : At line:15 char:6
                        +      Connect-AzAccount -Credential $credentials -TenantId $tenantID - .
                        +      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot          :
PSCommandPath         :
InvocationName        : Connect-AzAccount
PipelineLength        : 0
PipelinePosition      : 0
ExpectingInput        : False
CommandOrigin         : Internal
DisplayScriptPosition :

需要执行PowerShell脚本,以便可以在同一PowerShell脚本中执行经过身份验证的PowerShell命令。它是一个侦听服务总线的网络工作线程,然后执行PowerShell。最终将被容器化

h79rfbju

h79rfbju1#

我创建了一个控制台应用程序:-

从Azure门户复制订阅ID。
在订阅级别为我分配了服务主要参与者角色,以便它执行订阅级别的任务以及读取、写入订阅。
在我的订阅中〉访问控制(IAM)-〉角色分配〉授予SP的贡献者访问权限。

您可以通过单击“在访问控制(IAM)页面中添加角色分配”〉“选择角色贡献者”〉“选择成员”〉“您的SP”〉“选择”〉“审阅+创建”来提供对SP的贡献者访问权限。

从此处获取SP租户ID和应用程序ID:-

在Powershell命令中添加这些参数。
在VisualStudio中创建了简单的控制台应用程序。

已安装Microsoft.Powershell.SDK NuGet软件包7.21.1版本。

在VS studio的调试〉常规设置中禁用启用仅我的代码。

从Program.cs中的.net控制台应用程序运行Powershell的简单程序:

using System.Diagnostics;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Xml.Linq;
using System;

var initialState = InitialSessionState.CreateDefault2();
initialState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

using  var ps = PowerShell.Create(initialState);

var results = ps.AddScript("\r\nInstall-Module Az.Accounts\r\nInstall-Module Az.esources\r\nImport-Module Az.Accounts\r\nImport-Module Az.Resources\r\n\r\nClear-AzContext -Force \r\n\r\n$tenantID = \"83331f4e-7f45-4ce4-99ed-af9038592395\" \r\n$subscriptionID = \"0151c365-f598-44d6-b4fd-e2b6e97cb2a7\"\r\n\r\n $azureAplicationId = \"c0c952e9-5254-45b5-b838-6d26a31435cb\";\r\n $azurePassword = ConvertTo-SecureString \"Mom8Q~AX1xc9OlrUislxBJvTvbfUKuWtpO9gadfE\" -AsPlainText -Force; \r\n $credentials = New-Object System.Management.Automation.PSCredential($azureAplicationId, $azurePassword); \r\n\r\ntry \r\n{ \r\n Connect-AzAccount -Credential $credentials -TenantId $tenantID -ServicePrincipal -ErrorAction Stop\r\n New-AzResourceGroup -Name RG05 -Location \"South Central US\"\r\n}\r\ncatch \r\n{ \r\n Write-Error $Exception ; \r\n}\r\n").Invoke();

通过以上代码,我能够使用服务主体成功连接到我的Azure帐户,我还添加了一个命令来使用服务主体创建资源组,并且资源组是在构建成功后在Azure门户上创建的。
在PowerShell中添加了以下代码行,以便在导入之前先安装PowerShell模块。

Install-Module  Az.Accounts
Install-Module  Az.Resources
Import-Module  Az.Accounts
Import-Module  Az.Resources

添加了一个在Azure Portal中创建新资源组的命令,以验证服务主体是否正在Azure中进行身份验证和创建资源。

PowerShell命令已成功在本地运行,并且已在Azure Portal上创建资源组RG 03。

现在,我通过.NET控制台应用程序运行了相同的命令,构建成功地向Azure进行了身份验证,并创建了一个RG。

相关问题