Set-AzDiagnosticSetting - Skip 'metricsCategory' for Azure databricks - azure

I have the below 'generic' code that sets the diagnostic setting for all my Azure resources. However, I am not able to use it for Azure Databricks, as the Azure databricks does not have 'MetricsCategory' but just the log category.
How can I bypass the 'MetricCategory' in the '$diagParams' parameter. I do not want to change the entire function just for Azure Databricks. It defeats the very purpose I created the Generic Function.
Code:
$diagParams = #{
Name = "coemonitoreu"
ResourceId = "/subscriptions/-f30a-4bfd-a6be-1c59594b8592/resourcegroups/manjug-dev/providers/Microsoft.Databricks/workspaces/manjug-adbv-dev"
StorageAccountId = "/subscriptions/-2ad9-4167-b9f2-45be0e48c465/resourcegroups/-monitor-dev/providers/microsoft.storage/storageaccounts/monitorblobdev"
WorkspaceId = "/subscriptions/-2ad9-4167-b9f2-45be0e48c465/resourcegroups/-monitor-dev/providers/microsoft.operationalinsights/workspaces/diag-dev"
MetricCategory = #("AllMetrics")
Category = #("dbfs", "clusters", "accounts", "jobs", "notebook", "ssh", "workspace", "secrets", "sqlPermissions", "instancePools")
Enabled = $true
RetentionEnabled = $true
RetentionInDays = 0
}
$DebugPreference = 'continue'
Set-AzDiagnosticSetting #diagParams
I get the error, because I am mentioning 'metrics' in my parameter set. And this is not consumed by Azure databricks diagnostic setting.
Set-AzDiagnosticSetting : Exception type: ErrorResponseException, Message: Null/Empty, Code: BadRequest, Status code:BadRequest, Reason phrase: Bad Request
At line:14 char:1
+ Set-AzDiagnosticSetting #diagParams
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzDiagnosticSetting], PSInvalidOperationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Insights.Diagnostics.SetAzureRmDiagnosticSettingCommand
DEBUG: AzureQoSEvent: CommandName - Set-AzDiagnosticSetting; IsSuccess - False; Duration - 00:00:01.8132017; Exception - System.Management.Automation.PSInvalidOperationEx
ception: Exception type: ErrorResponseException, Message: Null/Empty, Code: BadRequest, Status code:BadRequest, Reason phrase: Bad Request ---> Microsoft.Azure.Management
.Monitor.Models.ErrorResponseException: Operation returned an invalid status code 'BadRequest'
at Microsoft.Azure.Management.Monitor.DiagnosticSettingsOperations.<CreateOrUpdateWithHttpMessagesAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Azure.Management.Monitor.DiagnosticSettingsOperationsExtensions.<CreateOrUpdateAsync>d__3.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.Azure.Commands.Insights.MonitorCmdletBase.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();
DEBUG: Finish sending metric.
DEBUG: 5:38:51 AM - SetAzureRmDiagnosticSettingCommand end processing.
DEBUG: 5:38:51 AM - SetAzureRmDiagnosticSettingCommand end processing.

Well, to create an exclusion you should use if statement:
if ($diagParam.resourceId -match 'DataBricks') {
$diagParams.Remove('MetricCategory')
}

Related

TokenHelper Error with Connect-PnPOnline in powerShell Azure Function

Currently, I'm Using the Connect-PnPOnline in a Powershell script:
Connect-PnPOnline -ClientId $tenant_client_id -ClientSecret $tenant_client_secret -Url $TenantUrl
When I run this code in the Windows PowerShell ISE, Works perfectly but if I try to run this in an Azure function this error appears:
ERROR: The type initializer for 'OfficeDevPnP.Core.Utilities.TokenHelper' threw an exception.
Exception :
Type : System.TypeInitializationException
TypeName : OfficeDevPnP.Core.Utilities.TokenHelper
TargetSite :
Name : ProcessRecord
DeclaringType : PnP.PowerShell.Commands.Base.ConnectOnline
MemberType : Method
Module : PnP.PowerShell.Online.Commands.dll
StackTrace :
at PnP.PowerShell.Commands.Base.ConnectOnline.ProcessRecord()
at System.Management.Automation.Cmdlet.DoProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
Message : The type initializer for 'OfficeDevPnP.Core.Utilities.TokenHelper' threw an exception.
Data : System.Collections.ListDictionaryInternal
InnerException :
Type : System.TypeLoadException
Message : Could not load type 'System.Web.Configuration.WebConfigurationManager' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
TypeName : System.Web.Configuration.WebConfigurationManager
TargetSite : Void .cctor()
StackTrace :
at OfficeDevPnP.Core.Utilities.TokenHelper..cctor()
Source : OfficeDevPnP.Core
HResult : -2146233054
Source : PnP.PowerShell.Online.Commands
HResult : -2146233036
CategoryInfo : NotSpecified: (:) [Connect-PnPOnline], TypeInitializationException
FullyQualifiedErrorId : System.TypeInitializationException,PnP.PowerShell.Commands.Base.ConnectOnline
InvocationInfo :
MyCommand : Connect-PnPOnline
ScriptLineNumber : 36
OffsetInLine : 1
HistoryId : 1
I need to use the Credential ID and The Client Secret to authenticate.
You may need to switch your Azure function to Version 1.0.
According to documentation version 2 is .NET Core 2 and function app version 1.0 ~. That should be the cause why it prompt "Could not load type 'System.Web.Configuration.WebConfigurationManager'.

Creating Azure VirtualMachineExtension failure

I have a Windows Machine that I want to add VM extension using the azure python SDK , I send the following request
{'location': 'westus',
'tags': None,
'publisher': 'Microsoft.Compute',
'virtual_machine_extension_type': 'CustomScriptExtension',
'type_handler_version': '1.4',
'settings': '{
"file_uris": ["https://mysite.azurescripts.net/ps_enable_winrm_http.ps1"],
"command_to_execute": "powershell -ExecutionPolicy Unrestricted -file ps_enable_winrm_http.ps1"}'
}
but what happens is that it gives the following exception
configure virtual_machine '946b4246-a604-4b01-9e6a-09ed64a93bdb' failed with this error :
VM has reported a failure when processing extension '13da0dc5-09c0-4e56-a35d-fdbc42432e11'.
Error message: "Invalid handler configuration. Exiting.
Error Message: Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. "
More information on troubleshooting is available at https://aka.ms/VMExtensionCSEWindowsTroubleshoot
adding a simple code snippet that I use
vm_extension_name = "{0}".format(uuid4())
vm_extension_params = {
'location': location_val,
'tags': tags_val,
'publisher': 'Microsoft.Compute',
'virtual_machine_extension_type': 'CustomScriptExtension',
'type_handler_version': type_handler_version,
'auto_upgrade_minor_version': True,
'settings': json.dumps({
'fileUris': file_uris,
'commandToExecute': command_to_execute
})
}
logger.info("sending {0}".format(vm_extension_params))
any ideas , should I send something differently or am I missing something from the above request that cause the issue
thanks for the help in advance
Regards,
When we use python sdk to install custom script extension, we should create Object VirtualMachineExtension. Its parameter settings should be Object. But you define it as str. Please update it with removing ''. For more details, please refer to the document
For example
from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials
AZURE_TENANT_ID= ''
AZURE_CLIENT_ID=''
AZURE_CLIENT_SECRET=''
AZURE_SUBSCRIPTION_ID=''
credentials = ServicePrincipalCredentials(client_id=AZURE_CLIENT_ID,secret=AZURE_CLIENT_SECRET,tenant=AZURE_TENANT_ID)
compute_client = ComputeManagementClient(credentials, AZURE_SUBSCRIPTION_ID)
resource_group_name='stan'
vm_name='win2016'
params_create = {
'location':'CentralUS',
'tags': None,
'publisher': 'Microsoft.Compute',
'virtual_machine_extension_type': 'CustomScriptExtension',
'type_handler_version': '1.4',
'settings':
{
'fileUris': ['https://***/test/test.ps1'],
'commandToExecute': 'powershell -ExecutionPolicy Unrestricted -File test.ps1'
}
}
ext_poller = compute_client.virtual_machine_extensions.create_or_update(
resource_group_name,
vm_name,
'test',
params_create,
)
ext = ext_poller.result()
print(ext)

TFS Release Powershell task to deploy to Sharepoint: "Cannot bind argument to parameter 'String' because it is null."

Edit:
I managed to get it to accept 1 parameter. Apparently it hates accepting 2. Now I've got another exception: remote server returning 401 unauthorized. I guess the solution for this is to not use more than 1 parameter, but that's not really a solution. Sounds like a bug to me.
Original question:
I'm at my wit's end on this one.
I have a powershell script that I'd like to execute during a Release that uploads an archived copy of the build to a document library in SharePoint. The build server that hosts TFS 2017 is running Powershell 4. When I RDP in and run the below script in ISE on the same server (precisely where TFS appears to be executing things in the tasks), it works, provided that I add the environment variables where they are commented in the script below.
When I run the same exact script (I'm running it from the drop folder) via TFS, it produces the error:
2017-10-17T13:48:52.5561597Z D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoint.ps1 D:\Integration_20171017.2.zip Integration_20171017.2
2017-10-17T13:48:53.0241597Z Connecting to http://sharepoint_server/sites/TFS_DefaultCollection/NET as srv_promote...
2017-10-17T13:48:53.2737597Z ##[error]D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoin
2017-10-17T13:48:53.2737597Z ##[error]t.ps1 : Cannot bind argument to parameter 'String' because it is null.
which is crazy, because you can clearly see the non-null arguments in the line executing the script.
I have tried specifying the type in the param section, like [string]$filePathToUpload. I have tried specifying the parameters in the command line arguments list, like .\publish_to_sharepoint.ps1 -filePathToUpload "..." -fileName "...", both with and without quotation marks.
One thing to note is when I try to run the task with an in-line powershell script-- because of the character limit, I can only paste up to the first "Write-Host" line-- it passes the parameter step without error and the release passes.
Is this a bug with TFS Powershell task? I can't wrap my head around where this error is coming from.
Thanks in advance. Below are the relevant details.
Powershell script:
param(
$filePathToUpload,
$fileName
)
#$Env:SharePointDomain = "..."
#$Env:SharePointBaseUrl = "http://sharepoint_server"
#$Env:SharePointSite = "/sites/TFS_DefaultCollection/NET/"
#$Env:SharePointUsername = "username"
#$Env:SharePointPassword = "password"
#$Env:SharePointLibrary = "library_name"
Add-Type -AssemblyName "Microsoft.SharePoint.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL"
Add-Type -AssemblyName "Microsoft.SharePoint.Client.Runtime, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL"
Write-Host 'Connecting to'$Env:SharePointBaseUrl$Env:SharePointSite' as '$Env:SharePointUsername'...'
try{
$sharepointFullUrl = $Env:SharePointBaseUrl + $Env:SharePointSite
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext $sharepointFullUrl
$clientContext.Credentials = New-Object System.Net.NetworkCredential $Env:SharePointUsername, (ConvertTo-SecureString $Env:SharePointPassword -AsPlainText -Force)
$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery();
$relDestFilePath = $Env:SharePointSite + $Env:SharePointLibrary + "/" + $fileName
$fStream = New-Object IO.FileStream $filePathToUpload ,'Open','Read','Read'
[Microsoft.SharePoint.Client.File]::SaveBinaryDirect($clientContext, $relDestFilePath, $fStream, $true)
Write-Host 'Successfully uploaded'$fileName' to SharePoint document library '$Env:SharePointLibrary'.'
}
catch {
Write-Error $_
}
Release Task Detail:
Release Environment Variables:
Powershell Task Log
2017-10-17T13:48:52.5405597Z . 'D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoint.ps1' D:\Integration_20171017.2.zip Integration_20171017.2
2017-10-17T13:48:52.5561597Z C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command "$env:PSModulePath= $env:PSModulePath + ';' + $([system.io.path]::combine($env:AGENT_HOMEDIRECTORY, 'agent\worker\modules')); try { [System.Security.Cryptography.ProtectedData] | Out-Null } catch { Write-Verbose 'Adding assemly: System.Security' ; Add-Type -AssemblyName 'System.Security' ; [System.Security.Cryptography.ProtectedData] | Out-Null } ; Invoke-Expression -Command ([System.Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect([System.Convert]::FromBase64String('AQAAANCMnd8BFdERjHoAwE/Cl+sAmMDwyguygfTgNLUK3BteusFUlUwAAAAACAAAAAAADZgAAwAAAABAAAACMb/7FzkttmPEf8rMCA10mAAAAAASAAACgAAAAEAAAAN7Pqk+I01BNW4lONiyiuhArrpBqYAAiGrvCfLy/fPm3YiAEuhiuhKwcUEIZFza2IcrqjhKCe4Qn8qRcPMfDEiw82ZUKdNYCrzUjayfThC97Vm3/lNgP15sgTr0NpJwsfvs7fz6zG3zwqwNeu4ivYzcYI/bYd+y608v+jh3d+8vzeQgyIGhto+9WcJlIaCnYv5qymVD7nTME8pnYz+DfNkP02s50jkCySimKgVHGIUAAAAkXCoQxu5+9njKHMCkhB2FSpdivg='), [System.Convert]::FromBase64String('McDlBBSayxJHIwJ35ERNNQ=='), [System.Security.Cryptography.DataProtectionScope]::CurrentUser))) ; if (!(Test-Path -LiteralPath variable:\LastExitCode)) { Write-Verbose 'Last exit code is not set.' } else { Write-Verbose ('$LastExitCode: {0}' -f $LastExitCode) ; exit $LastExitCode }"
2017-10-17T13:48:52.5561597Z Executing the following powershell script. (workingFolder = D:\BuildAgentWorkFolder\f00869677)
2017-10-17T13:48:52.5561597Z D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoint.ps1 D:\Integration_20171017.2.zip Integration_20171017.2
2017-10-17T13:48:53.0241597Z Connecting to http://sharepoint_server/sites/TFS_DefaultCollection/NET as srv_promote...
2017-10-17T13:48:53.2737597Z ##[error]D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepoin
2017-10-17T13:48:53.2737597Z ##[error]t.ps1 : Cannot bind argument to parameter 'String' because it is null.
2017-10-17T13:48:53.2737597Z ##[error]At line:1 char:1
2017-10-17T13:48:53.2737597Z ##[error]+ .
2017-10-17T13:48:53.2737597Z ##[error]'D:\BuildAgentWorkFolder\f00869677\Git\drop\publish_to_sharepo
2017-10-17T13:48:53.2737597Z ##[error]...
2017-10-17T13:48:53.2737597Z ##[error]+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2017-10-17T13:48:53.2737597Z ##[error]~~~
2017-10-17T13:48:53.2737597Z ##[error] + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep
2017-10-17T13:48:53.2737597Z ##[error] tion
2017-10-17T13:48:53.2737597Z ##[error] + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
2017-10-17T13:48:53.2737597Z ##[error] n,publish_to_sharepoint.ps1
2017-10-17T13:48:53.2737597Z ##[error]
2017-10-17T13:48:53.2737597Z ##[error]Process completed with exit code 0 and had 1 error(s) written to the error stream.
This is the issue: $Env:SharePointPassword. Secrets aren't stored as environment variables. Modify your script and pass in the password as a parameter.

IdentityServer4 with Asp.Net Identity and External Authentication fails to sign out

Steps to reproduce:
Download the asp.net identity quickstart:
https://github.com/IdentityServer/IdentityServer4.Samples/tree/dev/Quickstarts/6_AspNetIdentity
2.Add google authentication nuget package
Configure Google Authentication:
3a. In Startup.cs, ConfigureServices method:
services.AddIdentity<ApplicationUser, IdentityRole>(x=> { x.Cookies.ExternalCookie.AuthenticationScheme = "Google"; })
3b. In Startup.cs, Configure method:
app.UseIdentity();
app.UseIdentityServer();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
AutomaticAuthenticate = false,
AutomaticChallenge = false
});
app.UseGoogleAuthentication(new GoogleOptions
{
AuthenticationScheme = "Google",
SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
ClientId = "your client id",
ClientSecret = "your client secret"
});
Launch identity server and the mvc client. You should be able to login with google and register. Click the Logout button and you get the below error:
Specified method is not supported.
at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler1.HandleSignOutAsync(SignOutContext context) at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.d__63.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.d__14.MoveNext()
Any ideas on what could be wrong? Github issue here: https://github.com/IdentityServer/IdentityServer4/issues/530

Import-AzurePublishSettingsFile throws CryptographicException, Internal Error when called from IIS

I am experiencing a problem similar to the one described here:
Import-AzurePublishSettingsFile throws CryptographicException
We are calling Powershell from IIS to programmatically deploy VMs. Part of this process involves loading new Publish Settings Files in for new customers. We are getting the following error when attempting to do so:
Import-AzurePublishSettingsFile : An internal error occurred.
At C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps1:152 char:2
+ Import-AzurePublishSettingsFile ($outputDir + "\" + $azSettingsFile)
-ErrorActi ...
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:)
[Import-AzurePublishSettingsFile], CryptographicException
+ FullyQualifiedErrorId :
Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand
I have a hunch this has something to do with the user space, as if I run exactly the same script from an interactive PS session, on the same server, it works fine.
Any ideas on how to troubleshoot this?
Edit: Stack trace from Powershell:
PSMessageDetails :
Exception : System.Security.Cryptography.CryptographicException: An internal error occurred.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password)
at Microsoft.WindowsAzure.Commands.Utilities.Common.PublishSettingsImporter.PublishSubscriptionToAzureSubscription(PublishDataPublishProfile profile, PublishDataPublishProfileSubscription s) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\PublishSettingsImporter.cs:line 56
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Microsoft.WindowsAzure.Commands.Utilities.Common.WindowsAzureProfile.ImportPublishSettings(String fileName) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\WindowsAzureProfile.cs:line 293
at Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand.ImportFile(String fileName) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands\Subscription\ImportAzurePublishSettings.cs:line 95
at Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand.ExecuteCmdlet() in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands\Subscription\ImportAzurePublishSettings.cs:line 46
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletBase.ProcessRecord() in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\CmdletBase.cs:line 96
TargetObject :
CategoryInfo : CloseError: (:) [Import-AzurePublishSettingsFile],
CryptographicException
FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps1: line 163
PipelineIterationInfo : {}
MyCommand : Import-AzurePublishSettingsFile
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 163
OffsetInLine : 2
HistoryId : 1
ScriptName : C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps1
Line : Import-AzurePublishSettingsFile ($outputDir + "\" +
$azSettingsFile) -ErrorAction Stop
PositionMessage : At C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps
1:163 char:2
+ Import-AzurePublishSettingsFile ($outputDir + "\"
+ $azSettingsFile) -ErrorActi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot : C:\WebApps\Provisioning\PowerShellScripts
PSCommandPath : C:\WebApps\Provisioning\PowerShellScripts\vmDeploy.ps1
InvocationName : Import-AzurePublishSettingsFile
PipelineLength : 0
PipelinePosition : 0
ExpectingInput : False
CommandOrigin : Internal
DisplayScriptPosition :
00000000000000000000000000000000000000000000000000000000000000000000000000000000
Message : An internal error occurred.
Data : {}
InnerException :
TargetSite : Void ThrowCryptographicException(Int32)
StackTrace : at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle&pCertCtx)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password)
at Microsoft.WindowsAzure.Commands.Utilities.Common.PublishSettingsImporter.PublishSubscriptionToAzureSubscription(PublishDataPublishProfile profile, PublishDataPublishProfileSubscription s) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\PublishSettingsImporter.cs:line 56
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1source)
at Microsoft.WindowsAzure.Commands.Utilities.Common.WindowsAzureProfile.ImportPublishSettings(String fileName) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\WindowsAzureProfile.cs:line 293
at Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand.ImportFile(String fileName) in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands\Subscription\ImportAzurePublishSettings.cs:line 95
at Microsoft.WindowsAzure.Commands.Subscription.ImportAzurePublishSettingsCommand.ExecuteCmdlet() in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands\Subscription\ImportAzurePublishSettings.cs:line 46
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletBase.ProcessRecord() in c:\workspace\workspace\build-azure-sdk-tools-msi\WindowsAzurePowershell\src\Commands.Utilities\Common\CmdletBase.cs:line 96
HelpLink :
Source : mscorlib
HResult : -2146893792
Answer:
We changed the user context of the IIS app pool to a local administrator, and this resolved the issue. This suggests that the problem was access to the cryptographic store from the previous context. However the error and stack trace are too vague to confirm this hypothesis.
Using the WAML libraries for Compute, I'm able to deploy - however, I have to use slightly different credential loading:
X509Certificate2 certificate = new X509Certificate2(
Convert.FromBase64String(encodedCertificate),
"MyPrivateKey",
X509KeyStorageFlags.MachineKeySet);
Essentially I need to tell the system to load from the machine key set (even though my cert is local), and then the CryptographicException goes away.
I'm guessing this may be somewhat similar - even though you are using PowerShell, it is built on top of the WAML preview.
We had our build agent running on an Azure VM, it had been working fine but suddenly stopped working one day, apparently without any reason with the above error.
Logging on to the VM and running Import-AzurePublishSettingsFile "FileName" manually would run perfectly.
We found that our build agent was setup incorrectly and running under a user account who's MSDN credentials had changed.
We solved the problem firstly by restarting the VM - this will kill any Build Agent Processes running under other user accounts (in our case there was one and it was stopping us from running the next step below)
Next, it's best if you install the build agent as a service by running the script (as an administrator)
<agent home>/bin/service.install.bat file
You can check that the service is install by checking in Computer Management -> Services dialog that a Service called "Team City Agent" (or something similar is running), assuming everything else is setup ok your builds should start working (or at least get past the cryptographic error above :) )
More info can be found here: https://confluence.jetbrains.com/display/TCD8/Setting+up+and+Running+Additional+Build+Agents

Resources