azure-powershell icon indicating copy to clipboard operation
azure-powershell copied to clipboard

Splatting issues with complex PowerShell objects in New-AzureRmResourceGroupDeployment

Open blueelvis opened this issue 8 years ago • 25 comments

Description

Whenever we try passing complex objects (Like SecureString or array of hashtables etc), splatting does not work correctly for New-AzureRmResourceGroupDeployment & 'Test-AzureRmResourceGroupDeployment'

Script/Steps for Reproduction

  1. Create an ARM template. You can have a basic template accepting just a single "securestring" parameter.
  2. Use the below code and refer the template from Step 1.
  3. You will get the following error -

Code : InvalidTemplate Message : Deployment template validation failed: 'The provided value for the template parameter 'domainAdminPassword' at line '5' and column '28' is not valid.'. Details :

$pass = Read-Host 'Password?' -AsSecureString
Write-Output $pass
$params = @{
    'domainAdminPassword' = $pass
}

Test-AzureRmResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateUri $templateUri -TemplateParameterObject $params -Mode Incremental

Module Version

5.6.0

Environment Data

PS C:\Users\Pranav> $PSVersionTable

Name                           Value                                                                                                 
----                           -----                                                                                                 
PSVersion                      5.1.17134.48                                                                                          
PSEdition                      Desktop                                                                                               
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                               
BuildVersion                   10.0.17134.48                                                                                         
CLRVersion                     4.0.30319.42000                                                                                       
WSManStackVersion              3.0                                                                                                   
PSRemotingProtocolVersion      2.3                                                                                                   
SerializationVersion           1.1.0.1  

Debug Output


PS C:\Users\Pranav> $pass = Read-Host 'Password?' -AsSecureString
Write-Output $pass
$params = @{
    'domainAdminPassword' = $pass
}

Test-AzureRmResourceGroupDeployment -ResourceGroupName "Pranav-Test" -TemplateUri "https://pranavdevtest.blob.core.windows.net/devcontainer/Template.json?sp=r&st=2018-05-24T11:39:08Z&se=2018-05-24T19:39:08Z&spr=https&sv=2017-11-09&sig=7oqwb0rgicM1ROOvgW7Z%2FUamx8e78ooDjJHB2JyzLH0%3D&sr=b" -TemplateParameterObject $params -Mode Incremental -Debug
System.Security.SecureString
DEBUG: 17:20:23 - TestAzureResourceGroupDeploymentCmdlet begin processing with ParameterSet 'ByTemplateUriAndParameterObject'.
DEBUG: 17:20:24 - using account id '[email protected]'...
DEBUG: [Common.Authentication]: Authenticating using Account: '[email protected]', environment: 'AzureCloud', tenant: '2dfc6
a32-d03c-4504-8d69-f08da326f294'
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24: a226e195-3f4b-445c-a360-504a9f4b858f - AcquireTokenHandlerBase: === Token Acquisition started:
	Authority: https://login.microsoftonline.com/2dfc6a32-d03c-4504-8d69-f08da326f294/
	Resource: https://management.core.windows.net/
	ClientId: 1950a258-227b-4e31-a9cf-717495945fc2
	CacheType: Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache (6 items)
	Authentication Target: User
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 05/24/2018 11:50:24: a226e195-3f4b-445c-a360-504a9f4b858f - TokenCache: Looking up cache for a token...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24: a226e195-3f4b-445c-a360-504a9f4b858f - TokenCache: An item matching the requested resource was found in th
e cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 05/24/2018 11:50:24: a226e195-3f4b-445c-a360-504a9f4b858f - TokenCache: 50.4569744783333 minutes left until token in cache expi
res

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24: a226e195-3f4b-445c-a360-504a9f4b858f - TokenCache: A matching item (access token or refresh token or both)
 was found in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24: a226e195-3f4b-445c-a360-504a9f4b858f - AcquireTokenHandlerBase: === Token Acquisition finished successfull
y. An access token was retuned:
	Access Token Hash: kSoMv7qKQ8PgQq7mVmhl21WNdSm0btSVct/Tp0vSLdE=
	Refresh Token Hash: UDLM5+4zpOxm1qZeQ+zpwr3yF1i0PkHD3J0R/xkFwh0=
	Expiration Time: 05/24/2018 12:40:51 +00:00
	User Hash: xB4Q59Maresn7mH8Ub+nMs9cFQb/7j7XmTr72ZzC9Sw=
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24:  - TokenCache: Serializing token cache with 6 items.

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24: 9c549605-4f88-4c26-a9dc-dea483ad3b83 - AcquireTokenHandlerBase: === Token Acquisition started:
	Authority: https://login.microsoftonline.com/2dfc6a32-d03c-4504-8d69-f08da326f294/
	Resource: https://management.core.windows.net/
	ClientId: 1950a258-227b-4e31-a9cf-717495945fc2
	CacheType: Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache (6 items)
	Authentication Target: User
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 05/24/2018 11:50:24: 9c549605-4f88-4c26-a9dc-dea483ad3b83 - TokenCache: Looking up cache for a token...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24: 9c549605-4f88-4c26-a9dc-dea483ad3b83 - TokenCache: An item matching the requested resource was found in th
e cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 05/24/2018 11:50:24: 9c549605-4f88-4c26-a9dc-dea483ad3b83 - TokenCache: 50.4568247316667 minutes left until token in cache expi
res

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24: 9c549605-4f88-4c26-a9dc-dea483ad3b83 - TokenCache: A matching item (access token or refresh token or both)
 was found in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24: 9c549605-4f88-4c26-a9dc-dea483ad3b83 - AcquireTokenHandlerBase: === Token Acquisition finished successfull
y. An access token was retuned:
	Access Token Hash: kSoMv7qKQ8PgQq7mVmhl21WNdSm0btSVct/Tp0vSLdE=
	Refresh Token Hash: UDLM5+4zpOxm1qZeQ+zpwr3yF1i0PkHD3J0R/xkFwh0=
	Expiration Time: 05/24/2018 12:40:51 +00:00
	User Hash: xB4Q59Maresn7mH8Ub+nMs9cFQb/7j7XmTr72ZzC9Sw=
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 05/24/2018 11:50:24:  - TokenCache: Serializing token cache with 6 items.

DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
POST

Absolute Uri:
https://management.azure.com/subscriptions/66d477ee-6241-4568-9e3f-d533bd3a8953/resourcegroups/Pranav-Test/providers/Microsoft.Resourc
es/deployments/c18bbe04-5dd0-4b20-a912-85b29539e717/validate?api-version=2017-05-10

Headers:
x-ms-client-request-id        : ef348435-6f2d-477e-abc7-5f45f9ebb6d5
accept-language               : en-US

Body:
{
  "properties": {
    "templateLink": {
      "uri": "https://pranavdevtest.blob.core.windows.net/devcontainer/Template.json?sp=r&st=2018-05-24T11:39:08Z&se=20
18-05-24T19:39:08Z&spr=https&sv=2017-11-09&sig=7oqwb0rgicM1ROOvgW7Z%2FUamx8e78ooDjJHB2JyzLH0%3D&sr=b"
    },
    "parameters": {
      "domainAdminPassword": {
        "value": {
          "CliXml": "<Objs Version=\"1.1.0.1\" xmlns=\"http://schemas.microsoft.com/powershell/2004/04\">\r\n  <SS>01000000d08c9ddf011
5d1118c7a00c04fc297eb010000007c5d4159e752934a9d87c1c864d8c9840000000002000000000010660000000100002000000027a4bf480517b136272da6f77454c
6a1e97d06b786db39cbc625516d602b0526000000000e80000000020000200000004b39d41cf204b3be7597634762d3d1cc6b3bd53a2e25cfe7ffe9f83d46ffa992200
00000ad880112a50938a963067243799e95455bcb46cd09659907037cf7a86ad3ab4840000000f2cacfd64d7289b0aa5ff791d290734292ffcef6f510f88102019e0db
fe8be2cf6c8657b9ee82449c5ae9df9a07fc0f254bed9e8aecb55846d4726d36ebf6298</SS>\r\n</Objs>"
        }
      }
    },
    "mode": "Incremental"
  }
}


DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
BadRequest

Headers:
Pragma                        : no-cache
x-ms-failure-cause            : gateway
x-ms-ratelimit-remaining-subscription-writes: 1198
x-ms-request-id               : f1973795-f609-4f2c-a08e-5aab3e09ca9a
x-ms-correlation-request-id   : f1973795-f609-4f2c-a08e-5aab3e09ca9a
x-ms-routing-request-id       : CENTRALINDIA:20180524T115026Z:f1973795-f609-4f2c-a08e-5aab3e09ca9a
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Thu, 24 May 2018 11:50:25 GMT

Body:
{
  "error": {
    "code": "InvalidTemplate",
    "message": "Deployment template validation failed: 'The provided value for the template parameter 'domainAdminPassword' at line '5
' and column '28' is not valid.'."
  }
}




Code    : InvalidTemplate
Message : Deployment template validation failed: 'The provided value for the template parameter 'domainAdminPassword' at line '5' 
          and column '28' is not valid.'.
Details : 

DEBUG: AzureQoSEvent: CommandName - Test-AzureRmResourceGroupDeployment; IsSuccess - True; Duration - 00:00:04.0759707; Exception - ;
DEBUG: Finish sending metric.
DEBUG: 17:20:28 - TestAzureResourceGroupDeploymentCmdlet end processing.
DEBUG: 17:20:28 - TestAzureResourceGroupDeploymentCmdlet end processing.

Please do note that if you do the following, then the error does not occur (One of the ways which I am using right now but they are not ideal) -

  1. Pass the parameter explicitly to Test-AzureRmResourceGroupDeployment like this `Test-AzureRmResourceGroupDeployment -domainAdminPassword $pass ....' . Then this would work fine.
  2. To the Template parameter object, do the following $params.Add('domainAdminPassword',$pass) . If you pass this directly to 'Test-AzureRmResourceGroupDeployment', it will work.

blueelvis avatar May 24 '18 11:05 blueelvis

@cormacpayne - Any idea what could be happening in this case?

blueelvis avatar May 30 '18 09:05 blueelvis

@blueelvis Can you include the debug stream when this works in case 2 (you use Add to add the parameter to the template parameter object)?

It appears that the transformation of TemplateParameterObject is simply incorrect, and I'd like to see a valid request usign this parameter.

markcowl avatar Jul 27 '18 00:07 markcowl

@markcowl - Sure thing. Please find it below.

Code used -


$pass = Read-Host 'Password?' -AsSecureString
Write-Output $pass

$params = @{}
$params.Add("domainAdminPassword",$pass)

Test-AzureRmResourceGroupDeployment -ResourceGroupName "Pranav-DevTest-Central" -TemplateUri "https://pranavdevtest.blob.core.windows.net/devcontainer/XzVMDomainJoin.json?sp=r&st=2018-07-31T09:37:12Z&se=2018-07-31T17:37:12Z&spr=https&sv=2017-11-09&sig=8%2Bw2SelCbB01k0q4n6Oj7QO0rpEBcu0%3D&sr=b" -TemplateParameterObject $params -Mode Incremental -Debug

PS C:\Users\Pranav> $pass = Read-Host 'Password?' -AsSecureString
Write-Output $pass

$params = @{}
$params.Add("domainAdminPassword",$pass)

Test-AzureRmResourceGroupDeployment -ResourceGroupName "Pranav-DevTest-Central" -TemplateUri "https://pranavdevtest.blob.core.windows.net/devcontainer/XzVMDomainJoin.json?sp=r&st=2018-07-31T09:37:12Z&se=2018-07-31T17:37:12Z&spr=https&sv=2017-11-09&sig=8%2Bw2SelCbB014n6Oj7QO0rpEBcu0%3D&sr=b" -TemplateParameterObject $params -Mode Incremental -Debug
System.Security.SecureString
DEBUG: 15:13:48 - TestAzureResourceGroupDeploymentCmdlet begin processing with ParameterSet 'ByTemplateUriAndParameterObject'.
DEBUG: 15:13:50 - using account id '[email protected]'...
DEBUG: [Common.Authentication]: Authenticating using Account: '[email protected]', environment: 'AzureCloud', tenant: '2dfc6
a32-d03c-4504-8d69-f08da326f294'
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50: 48ba899e-e3e7-441b-ae07-833c5cf7bddc - AcquireTokenHandlerBase: === Token Acquisition started:
	Authority: https://login.microsoftonline.com/2dfc6a32-d03c-4504-8d69-f08da326f294/
	Resource: https://management.core.windows.net/
	ClientId: 1950a258-227b-4e31-a9cf-717495945fc2
	CacheType: Microsoft.Azure.Commands.Common.Authentication.ProtectedFileTokenCache (7 items)
	Authentication Target: User
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50:  - TokenCache: Deserialized 7 items to token cache.

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 07/31/2018 09:43:50: 48ba899e-e3e7-441b-ae07-833c5cf7bddc - TokenCache: Looking up cache for a token...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50: 48ba899e-e3e7-441b-ae07-833c5cf7bddc - TokenCache: An item matching the requested resource was found in th
e cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 07/31/2018 09:43:50: 48ba899e-e3e7-441b-ae07-833c5cf7bddc - TokenCache: 54.9124701666667 minutes left until token in cache expi
res

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50: 48ba899e-e3e7-441b-ae07-833c5cf7bddc - TokenCache: A matching item (access token or refresh token or both)
 was found in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50: 48ba899e-e3e7-441b-ae07-833c5cf7bddc - AcquireTokenHandlerBase: === Token Acquisition finished successfull
y. An access token was retuned:
	Access Token Hash: rbc+hAqYkIOzUypA7Uk5isShEWxQVo=
	Refresh Token Hash: GrYAgVIL4eme0UPKQFkZ+4V0jNnm1Ls2yw=
	Expiration Time: 07/31/2018 10:38:45 +00:00
	User Hash: xB4Q59Maresn7+nMs9cFQb/7j7XmTr72ZzC9Sw=
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50: 8608620e-a0ac-440d-aa98-4e1c709a497b - AcquireTokenHandlerBase: === Token Acquisition started:
	Authority: https://login.microsoftonline.com/2dfc6a32-d03c-4504-8d69-f08da326f294/
	Resource: https://management.core.windows.net/
	ClientId: 1950a258-227b-4e31-a9cf-717495945fc2
	CacheType: Microsoft.Azure.Commands.Common.Authentication.ProtectedFileTokenCache (7 items)
	Authentication Target: User
	

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50:  - TokenCache: Deserialized 7 items to token cache.

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 07/31/2018 09:43:50: 8608620e-a0ac-440d-aa98-4e1c709a497b - TokenCache: Looking up cache for a token...

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50: 8608620e-a0ac-440d-aa98-4e1c709a497b - TokenCache: An item matching the requested resource was found in th
e cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 
DEBUG: 07/31/2018 09:43:50: 8608620e-a0ac-440d-aa98-4e1c709a497b - TokenCache: 54.9121203816667 minutes left until token in cache expi
res

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50: 8608620e-a0ac-440d-aa98-4e1c709a497b - TokenCache: A matching item (access token or refresh token or both)
 was found in the cache

DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 
DEBUG: 07/31/2018 09:43:50: 8608620e-a0ac-440d-aa98-4e1c709a497b - AcquireTokenHandlerBase: === Token Acquisition finished successfull
y. An access token was retuned:
	Access Token Hash: rbiq2PBEMmoAqYkIOzUypA9aV7Uk5isShEWxQVo=
	Refresh Token Hash: GrYAD1LGgVIL4eme0UPKQFkZ+4V0jNnm1Ls2yw=
	Expiration Time: 07/31/2018 10:38:45 +00:00
	User Hash: xB4Q59MH8Ub+nMs9cFQb/7j7XmTr72ZzC9Sw=
	

DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
POST

Absolute Uri:
https://management.azure.com/subscriptions/66d477ee-6241-4568-9e3f-d533bd3a8953/resourcegroups/Pranav-DevTest-Central/providers/Micros
oft.Resources/deployments/32b104eb-8bcc-46b8-bc8c-efab8f3c0f8a/validate?api-version=2017-05-10

Headers:
x-ms-client-request-id        : 41c0a0c7-3736-41a6-a488-22605a89bfb0
accept-language               : en-US

Body:
{
  "properties": {
    "templateLink": {
      "uri": "https://pranavdevtest.blob.core.windows.net/devcontainer/XzVMDomainJoin.json?sp=r&st=2018-07-31T09:37:12Z&se=2018-07-31T
17:37:12Z&spr=https&sv=2017-11-09&sig=8%2Bw2SelCbB01%2BTk0q4n6Oj7QO0rpEBcu0%3D&sr=b"
    },
    "parameters": {
      "domainAdminPassword": {
        "value": "sample@12345%"
      }
    },
    "mode": "Incremental"
  }
}


DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-subscription-writes: 1199
x-ms-request-id               : a6045a89-2d6e-4460-9cda-cdc8c7d8f54f
x-ms-correlation-request-id   : a6045a89-2d6e-4460-9cda-cdc8c7d8f54f
x-ms-routing-request-id       : CANADAEAST:20180731T094352Z:a6045a89-2d6e-4460-9cda-cdc8c7d8f54f
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Tue, 31 Jul 2018 09:43:51 GMT

Body:
{
  "id": "/subscriptions/66d477ee-6241-4568-9e3f-d533bd3a8953/resourceGroups/Pranav-DevTest-Central/providers/Microsoft.Resources/deplo
yments/32b104eb-8bcc-46b8-bc8c-efab8f3c0f8a",
  "name": "32b104eb-8bcc-46b8-bc8c-efab8f3c0f8a",
  "properties": {
    "templateLink": {
      "uri": "https://pranavdevtest.blob.core.windows.net/devcontainer/XzVMDomainJoin.json?sp=r&st=2018-07-31T09:37:12Z&se=2018-07-31T
17:37:12Z&spr=https&sv=2017-11-09&sig=8%2Bw2SelCbB01qfU%2BTk0q4n6Oj7QO0rpEBcu0%3D&sr=b",
      "contentVersion": "1.0.0.0"
    },
    "templateHash": "4242749258223396685",
    "parameters": {
      "domainAdminPassword": {
        "type": "SecureString"
      }
    },
    "mode": "Incremental",
    "provisioningState": "Succeeded",
    "timestamp": "2018-07-31T09:43:52.0443723Z",
    "duration": "PT0S",
    "correlationId": "a6045a89-2d6e-4460-9cda-cdc8c7d8f54f",
    "providers": [
      {
        "namespace": "Microsoft.Compute",
        "resourceTypes": [
          {
            "resourceType": "virtualMachines/extensions",
            "locations": [
              "eastus"
            ]
          }
        ]
      }
    ],
    "dependencies": [],
    "validatedResources": [
      {
        "apiVersion": "2017-12-01",
        "id": "/subscriptions/66d477ee-6241-4568-9e3f-d533bd3a8953/resourceGroups/Pranav-DevTest-Central/providers/Microsoft.Compute/v
irtualMachines/PD-RHEL-02/extensions/-JOINDOMAIN",
        "name": "PD-RHEL-02/-JOINDOMAIN",
        "type": "Microsoft.Compute/virtualMachines/extensions",
        "location": "eastus",
        "properties": {
          "publisher": "Microsoft.Compute",
          "type": "JsonADDomainExtension",
          "typeHandlerVersion": "1.3",
          "autoUpgradeMinorVersion": true,
          "settings": {
            "Name": "contoso",
            "User": "contoso\\localAdmin",
            "Restart": "true",
            "Options": "3",
            "OUPath": "OU=Staging - Computers,OU=Servers,DC=contoso,DC=com"
          },
          "protectedsettings": {
            "Password": "sample@12345%"
          }
        }
      }
    ]
  }
}


VERBOSE: 15:13:53 - Template is valid.
DEBUG: AzureQoSEvent: CommandName - Test-AzureRmResourceGroupDeployment; IsSuccess - True; Duration - 00:00:08.6354902; Exception - ;
DEBUG: Finish sending metric.
DEBUG: 15:14:00 - TestAzureResourceGroupDeploymentCmdlet end processing.
DEBUG: 15:14:00 - TestAzureResourceGroupDeploymentCmdlet end processing.

Let me know what you think.

-Pranav

blueelvis avatar Jul 31 '18 09:07 blueelvis

@cormacpayne Sync up with Mark about this issue

MiYanni avatar Aug 14 '18 22:08 MiYanni

@Tiano2017 @ravbhatnagar would you guys mind taking a look? From looking at this for a bit, it appears that the type of the object passed to the -TemplateParameterObject parameter is the same in both scenarios (same values in the hashtable as well), but the request body is sending an inaccurate value for the adminDomainPassword property.

cormacpayne avatar Oct 18 '18 23:10 cormacpayne

I'm having this same issue with version 1.2.1 of Az.Resources (with Az 1.6.0). I'm working around the issue with the $params.Add("paramname", $secretValue) method.

migrande avatar Apr 03 '19 13:04 migrande

@cormacpayne @maddieclayton -- Is there any update on this issue?

blueelvis avatar Apr 03 '19 14:04 blueelvis

@cormacpayne @maddieclayton - It is now almost an year since this issue was opened and this is still happening. Any idea when this can be fixed permanently?

blueelvis avatar Apr 28 '19 20:04 blueelvis

Digging into this a little more, it appears the issue stems from the serialization of the parameter hashtable which includes this SecureString value. After this serialization, I found that the resulting string had two different values for the two different instantiations of the hashtable from the command line: (as you've seen from your examples provided) when creating an entry in the hashtable in-line, the value is schema text, but when creating an empty hashtable and adding the entry, the value is the expected "unwrapped" text. It appears there's some sort of underlying difference between how these two hashtables are treated in PowerShell.

@SteveL-MSFT @joeyaiello Hey guys, do you happen to know what the issue could be here? As a quick summary:

Scenario 1: The following hashtable is provided to the Test-AzResourceGroupDeployment cmdlet

PS C:\> $params = @{
    "domainAdminPassword" = $SecureStringPassword
}

When it's sent through JsonConvert.SerializeObject, the resulting string has a value of the following:

"CliXml": "<Objs Version=\"1.1.0.1\" xmlns=\"http://schemas.microsoft.com/powershell/2004/04\">\r\n  <SS>01000000d08c9ddf011
5d1118c7a00c04fc297eb010000007c5d4159e752934a9d87c1c864d8c9840000000002000000000010660000000100002000000027a4bf480517b136272da6f77454c
6a1e97d06b786db39cbc625516d602b0526000000000e80000000020000200000004b39d41cf204b3be7597634762d3d1cc6b3bd53a2e25cfe7ffe9f83d46ffa992200
00000ad880112a50938a963067243799e95455bcb46cd09659907037cf7a86ad3ab4840000000f2cacfd64d7289b0aa5ff791d290734292ffcef6f510f88102019e0db
fe8be2cf6c8657b9ee82449c5ae9df9a07fc0f254bed9e8aecb55846d4726d36ebf6298</SS>\r\n</Objs>"

Scenario 2: The following hashtable is provided to the same cmdlet

PS C:\> $params = @{}
PS C:\> $params.Add("domainAdminPassword", $SecureStringPassword)

When it's sent through JsonConvert.SerializeObject, the resulting string has a value equal to the convert string.

cormacpayne avatar May 09 '19 16:05 cormacpayne

Looking at the original repro, it's not splatting. I'm not familiar with this cmdlet, but assuming it has a -DomainAdminPassword parameter that takes a secure string, the right way to splat is to use this syntax:

cmdlet -otherparams @params

When using $params, it will literally pass the hashtable as a parameter value. When using @params then PowerShell will look into the hashtable and map the keys to parameters and the values as parameter values.

SteveL-MSFT avatar May 10 '19 04:05 SteveL-MSFT

@SteveL-MSFT - No, this doesn't have a parameter called DomainAdminPassword. That is something which I made up but yes, the commandlet does accept parameters like this.

blueelvis avatar May 20 '19 14:05 blueelvis

Need a simple PS repro if this is suspected in PowerShell. Testing this with splatting a secure string works with just PowerShell:

# splat.ps1
param ($ss)
$PasswordPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($ss)
$PlainTextPassword = [Runtime.InteropServices.Marshal]::PtrToStringUni($PasswordPointer)
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($PasswordPointer)
$PlainTextPassword
$ss = "foo" | ConvertTo-SecureString -AsPlainText -Force
$p = @{ ss = $ss }
./splat.ps1 @p

SteveL-MSFT avatar Jul 08 '19 16:07 SteveL-MSFT

@SteveL-MSFT this isn't really a splatting issue. The original poster called it splatting, but the issue is with passing SecureStrings via the TemplateParameterObject

migrande avatar Jul 08 '19 21:07 migrande

@migrande @SteveL-MSFT - Please feel free to change the title of this bug, but this is still reproducible.

blueelvis avatar Jul 13 '19 18:07 blueelvis

The following issues appear to be related: https://github.com/Azure/azure-powershell/issues/4856 and https://github.com/Azure/azure-powershell/issues/1528. They both refer to the CliXml value being generated for parameters passed to New-AzureRmResourceGroupDeployment, instead of a JSON object literal (such as would be generated by ConvertTo-Json). It appears to be happening both when -TemplateParameterObject is used, as well as "dynamic" parameters (including the hashtable splatting technique discussed in this issue - for example, "@parameters"). It would be awesome to have some progress on this issue (#1528 has been open since December 2015!) - what can we do to help figure this out?

dgritsko avatar Jul 22 '19 19:07 dgritsko

It seems that when JsonConvert serializes a securestring, it ends up calling into PowerShell's clixml serializer. I think AzPS needs to handle the case where the serialized object is CliXml and call Import-CliXml to deserialize it.

SteveL-MSFT avatar Jul 23 '19 17:07 SteveL-MSFT

FWIW, I ran into this with a template deployment I've been working on. The template defined a string parameter for the resource ID of the sole DDoS protection plan in the target resource group. I was originally creating the parameter object basically like this:

$params = @{
    ddosResourceId = (Get-AzDdosProtectionPlan | Select-Object -ExpandProperty Id)
}
New-AzResourceGroupDeployment -ResourceGroupName "my-group" -TemplateFile "my-template.json" -TemplateParameterObject $params

This would fail with the error "The provided value for the template parameter 'ddosResourceId' is not valid", and looking at the debug output, I could see that my template parameter object was a serialized CliXml object.

Using tidbits from this issue and other related issues, I think I was able to find a barebones set of examples that explain at least when this behavior happens. I'm leaving this note here in case it helps others in finding fixes and/or workarounds.

The issue as others pointed out is that JsonCovert.SerializeObject will sometimes call the CliXml serializer, which happens (as far as I can tell) when PowerShell has wrapped the object in question as a PSObject. Below are a couple of quick examples that show what happens with a raw string versus one forcibly wrapped as a PSObject (this is in PowerShell Core 6.2).

PS> $str = "value"
PS> $str -is [string]
True
PS> $str -is [PSObject]
False
PS> $h = @{ "key" = $str }
PS> [NewtonSoft.Json.JsonConvert]::SerializeObject( $h )
{"key":"myvalue"}
PS>
PS> $strAsPSObject = [PSObject]"value"
PS> $strAsPSObject -is [string]
True
PS> $strAsPSObject -is [PSObject]
True
PS> $h = @{ "key" = $strAsPSObject }
PS> [NewtonSoft.Json.JsonConvert]::SerializeObject( $h )
{"key":{"CliXml":"<Objs Version=\"1.1.0.1\" xmlns=\"http://schemas.microsoft.com/powershell/2004/04\">\r\n  <Obj RefId=\"0\">\r\n    <S>myvalue</S>\r\n  </Obj>\r\n</Objs>"}}
PS>
PS> $h = @{ "key" = $strAsPSObject.PSObject.BaseObject }
PS> [NewtonSoft.Json.JsonConvert]::SerializeObject( $h )
{"key":"myvalue"}

The last few lines basically show that unwrapping the PSObject gets you the desired serialization. Going back to the my original example, it turned out that PowerShell was wrapping what I thought was the resource ID string as a PSObject. I don't know the rules for when that wrapping will occur, but it seems that unconditionally calling .PSObject.BaseObject is safe to do, but that can get annoying verbose. In addition to doing the manual unwrapping or using the Add method on the Hashtable, I found also quoting the value and using a $(…) expression within the string helps coerce the value as a string, though that's not something that would work in all cases. Here's one last set of examples showing how JsonConvert.SerializeObject behaves in each of these different situations:

PS> $id = Get-AzDdosProtectionPlan | Select-Object -ExpandProperty Id
PS> $id
my-ddos-id
PS> $id -is [string]
True
PS> $id -is [PSObject]
True
PS> $h = @{
    "rawId" = $id
    "unwrappedId" = $id.PSObject.BaseObject
    "quotedId" = "$(Get-AzDdosProtectionPlan | Select-Object -ExpandProperty Id)"
}
PS> $h.Add( "addedId", $id )
PS> [NewtonSoft.Json.JsonConvert]::SerializeObject( $h )
{"addedId":"my-ddos-id",
"unwrappedId":"my-ddos-id",
"rawId":{"CliXml":"<Objs Version=\"1.1.0.1\" xmlns=\"http://schemas.microsoft.com/powershell/2004/04\">\r\n  <S>my-ddos-id</S>\r\n</Objs>"},
"quotedId":"my-ddos-id"}

Long story short, if your template parameter object has a parameter serialized as some CliXml string, it's because (as far as I can tell) PowerShell has wrapped your parameter value as PSObject. Using one of the above approaches should shed that wrapping and avoid the CliXml serializer from being called.

mvromer avatar Aug 16 '19 03:08 mvromer

@rthorn17 @SteveL-MSFT @maddieclayton - This still hasn't been resolved :(

blueelvis avatar Dec 16 '19 12:12 blueelvis

@alex-frankel Can you and the team take a look please. Thanks

rthorn17 avatar Dec 20 '19 17:12 rthorn17

I've experienced the same issue with the Set-AzVmExtension cmdlet. It has the -Settings parameter which expects a hash table. When I pass a value of @{workspaceId = $workspace.CustomerId } where $workspace.CustomerId is GUID, command works. When I pass a value of @{workspaceId = $workspace.CustomerId.Guid } where $workspace.CustomerId.Guid is a string, command fails.

If case of $workspace.CustomerId.Guid what gets assigned to the settings of the failed extension is:

PublicSettings          : {
                            "workspaceId": {
                              "CliXml": "<Objs Version=\"1.1.0.1\" xmlns=\"http://schemas.microsoft.com/powershell/2004/04\">\r\n
                          <S>061421ea-eb7a-48ef-a0ef-d6f7ce055b49</S>\r\n</Objs>"
                           
                          }

alexandair avatar Feb 03 '20 01:02 alexandair