Getting an error on my Terraform deployment for the following. I think it's because it's using a mixture of Terraform variables and Powershell I may have confused myself on the syntax.
Here is the Code:
data "template_file" "ad-join-template" {
template = <<EOF
<powershell>
# Set-DefaultAWSRegion -Region eu-west-2
# Set-Variable -name instance_id -value (Invoke-Restmethod -uri http://169.254.169.254/latest/meta-data/instance-id)
# # New-SSMAssociation -target key=InstanceIds,Values=$instance_id -Name "${aws_ssm_document.ad-join-domain.name}"
# New-SSMAssociation `
# -Name ad-join-domain `
# -Target #{
# "Key"="InstanceIds"
# "Values"="$($instance_id)"
# }
$apiurl = "${var.API}"
$tajdns = #("${taj_dns_server[0]}","[${taj_dns_server[1]}")
$count = 0
foreach ($dns in $tajdns){
$returnedRecords = (Resolve-DnsName -Name $apiurl -Server $dns).IPAddress
New-Variable -Name "dnsRecords$count" -Value $returnedRecords -Force
$count++
}
$allDNSrecords += $dnsRecords0
$allDNSrecords += $dnsRecords1
$allDNSrecords = $allDNSrecords | Select-Object -Unique
Add-Content C:\windows\system32\drivers\etc\hosts "`n***.**.*.* ssm.eu-west-2.amazonaws.com `
`n***.**.*.* ssm.eu-west-2.amazonaws.com `
`n***.**.*.* ssm.eu-west-2.amazonaws.com `
`n***.**.*.* ssmmessages.eu-west-2.amazonaws.com `
`n***.**.*.* ssmmessages.eu-west-2.amazonaws.com `
`n***.**.*.* ssmmessages.eu-west-2.amazonaws.com `
`n$allDNSrecords[0] ${var.API}`
`n$allDNSrecords[1] ${var.API}"
$nicDetails = Get-NetAdapter
Set-DnsClientServerAddress -InterfaceIndex $nicDetails.ifIndex -ServerAddresses (${local.concat_dns_servers_join})
$domain = "${aws_directory_service_directory.ad.name}"
$password = "${aws_directory_service_directory.ad.password}" | ConvertTo-SecureString -asPlainText -Force
$username = "admin#$($domain)"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Add-Computer -DomainName $domain -Credential $credential
Restart-Computer -Force
</powershell>
EOF
}
In the [${taj_dns_server[0]}]" this is pulling a Terraform variable out of list and populating it in to the script. Can you see if my syntax is correct?
Here is the Error:
│ Error: Invalid reference
136│
137│ on asg.tf line 19, in data "template_file" "ad-join-template":
138│ 19: $tajdns = #("[${taj_dns_server[0]}]","[${taj_dns_server[1]}]")
139│
140│ A reference to a resource type must be followed by at least one attribute
141│ access, specifying the resource name.
142╵
143╷
144│ Error: Invalid reference
145│
146│ on asg.tf line 19, in data "template_file" "ad-join-template":
147│ 19: $tajdns = #("[${taj_dns_server[0]}]","[${taj_dns_server[1]}]")
148│
149│ A reference to a resource type must be followed by at least one attribute
150│ access, specifying the resource name.
151╵
Related
i'm trying to create with powershell and and command new-AzResources some object, like probe, rules etc.. inside an application gateway. I'm using following snippet:
### Get properties
$get = Get-AzResource -ResourceType Microsoft.Network/applicationGateways -Name appgw -ResourceGroupName rgappgw
$user.Properties.probes.Properties
$properties = #{
protocol = 'Http';
path = '/';
interval = '30';
timeout = '30';
unhealthyThreshold = '3';
pickHostNameFromBackendHttpSettings = $true;
minServers = '0';
match = '200-399';
}
$SlotParams = #{
ResourceName = "appGwName"
Location = "West Europe"
ResourceGroupName = "AppGwRg"
ResourceType = "Microsoft.Network/applicationGateways/probes/probename" ####name of probes
PropertyObject = $properties
}
$execution = New-AzResource #SlotParams -Force
but i'm getting following error:
New-AzResource:
Line |
23 | $getSlotApse = New-AzResource #SlotParams -Force
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| {
"Message": "No HTTP resource was found that matches the request URI 'https://westeurope.network.azure.com:30058/123-124-14-4444-4444444/444444444444/subscriptions/mysubs/resourceGroups/AppGwRg/providers/Microsoft.Network/applicationGateways/appGwName/probes/probename?api-version=2022-07-01'."
}
CorrelationId: 12939812312831983
i use same logic to create app service but i'm not understand what i'm doing wrong with application gateway. Can you please give me an advice?
Thanks
I have reproduced in my environment and taken below commands from the Microsoft-Document:
The command or script which you provided are giving errors for me so, I have used below script for creating application gateway.
Firstly, I have created Subnet then Vnet and all the other required resources using below commands:
Update-Module Az.Network
Connect-AzAccount
$subnet = New-AzVirtualNetworkSubnetConfig -Name subnet01 -AddressPrefix 10.0.0.0/24 -WarningAction Ignore
$vnet = New-AzVirtualNetwork -Name appgwvnet -ResourceGroupName "rithwik-resources" -Location 'East US' -AddressPrefix 10.0.0.0/16 -Subnet $subnet
$subnet = $vnet.Subnets[0]
$publicip = New-AzPublicIpAddress -ResourceGroupName "rithwik-resources" -Name publicIP01 -Location 'East US' -AllocationMethod Dynamic
$gipconfig = New-AzApplicationGatewayIPConfiguration -Name rithwikgatewayIP -Subnet $subnet -WarningAction Ignore
$pool = New-AzApplicationGatewayBackendAddressPool -Name pool01 -BackendIPAddresses 134.170.185.46, 134.170.188.221, 134.170.185.50 -WarningAction Ignore
$probe = New-AzApplicationGatewayProbeConfig -Name probe01 -Protocol Http -HostName 'test.com' -Path '/path/path.htm' -Interval 30 -Timeout 120 -UnhealthyThreshold 8 -WarningAction Ignore
$poolSetting = New-AzApplicationGatewayBackendHttpSettings -Name rithwikapps -Port 80 -Protocol Http -CookieBasedAffinity Disabled -Probe $probe -RequestTimeout 80 -WarningAction Ignore
$fp = New-AzApplicationGatewayFrontendPort -Name frontendport01 -Port 80 -WarningAction Ignore
$fipconfig = New-AzApplicationGatewayFrontendIPConfig -Name fipconfig01 -PublicIPAddress $publicip -WarningAction Ignore
$listener = New-AzApplicationGatewayHttpListener -Name listener01 -Protocol Http -FrontendIPConfiguration $fipconfig -FrontendPort $fp -WarningAction Ignore
$rule = New-AzApplicationGatewayRequestRoutingRule -Name rule01 -RuleType Basic -BackendHttpSettings $poolSetting -HttpListener $listener -BackendAddressPool $pool -WarningAction Ignore
$sku = New-AzApplicationGatewaySku -Name Standard_Small -Tier Standard -Capacity 2 -WarningAction Ignore
$appgw = New-AzApplicationGateway -Name appgwtest -ResourceGroupName "rithwik-resources" -Location 'East US' -BackendAddressPools $pool -Probes $probe -BackendHttpSettingsCollection $poolSetting -FrontendIpConfigurations $fipconfig -GatewayIpConfigurations $gipconfig -FrontendPorts $fp -HttpListeners $listener -RequestRoutingRules $rule -Sku $sku -WarningAction Ignore
Output:
Once ran the above commands in powershell then the resources are created in Portal
I have a pipeline in which i calling a power-shell script which copy the azure keyvault secrets from one key-vault to another keyvault.
Here's the powershell script:
$SecretNames = "api-gateway--jwt-public-key",
"authentication-service--jwt-private-key",
"user-management--pen-password",
"user-management--stripe-secret-key"
$sourceVaultName="fdevcuskv03"
$destVaultName="fdevcuskv04"
for (($i = 0); $i -lt $SecretNames.Count; $i++)
{
$sourceSecretName = "$($SecretNames[$i])"
$destSecretName = "$($SecretNames[$i])"
$Getvalue=(Get-AzKeyVaultSecret -VaultName $sourceVaultName -Name $sourceSecretName).SecretValue
Write-Host "Copying $sourceSecretName Value To $destSecretName"
Set-AzKeyVaultSecret -VaultName $destVaultName -Name $destSecretName `
-SecretValue $Getvalue
}
When I run the pipeline, I got this error but this works fine locally.
Here's the error:
Get-AzKeyVaultSecret: /home/vsts/work/1/s/Terraform/Terraform-Scripts/main.ps1:351
Line |
351 | … $Getvalue=(Get-AzKeyVaultSecret -VaultName $sourceVaultName -Name $s …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Name or service not known
I'm bit confused, what i'm doing wrong.
Along with checking that please check also if the case maybe dns resolution issue or invalid dns cache causing the error .
For that please try to give it sleep time and repeat the step.(Also check by dns flush )
Place check azure-powershell issues(github) comment by #placidseven ang set azure keyvault by first checking if dns Is resolved.
foreach(($i = 0); $i -lt $SecretNames.Count; $i++)
{
$sourceSecretName = "$($SecretNames[$i])"
$destSecretName = $sourceSecretName
$Getvalue=(Get-AzKeyVaultSecret -VaultName $sourceVaultName -Name $sourceSecretName).SecretValue
Write-Host "Copying $sourceSecretName Value To $destSecretName"
setSecret
function setSecret{
while (!$secret) {
$DnsCheck = Resolve-DnsName $VaultURI -ErrorAction SilentlyContinue
if (!$DnsCheck) {
write-host "Resolve-DnsName taking time to resolve $vaultName. Keep trying!"
Start-Sleep -Seconds 30
Set-AzKeyVaultSecret -VaultName $destVaultName -Name $destSecretName `
-SecretValue $Getvalue -ErrorAction SilentlyContinue
}
}
$secret = Set-AzKeyVaultSecret -VaultName $destVaultName -Name $destSecretName `
-SecretValue $Getvalue -ErrorAction SilentlyContinue
setSecret
}
}
Reference: Set-AzureKeyVaultSecret does not recognize vaultName · GitHub
I'm trying to expose an endpoint using RestPS routes in powershell. I was able to expose it and run a custom PS script when an endpoint (http://localhost:8080/scan) is hit.
How do we pass body through routes & based on that value I need to execute the custom script.
RestPSroutes.json - Example
{
"RequestType": "GET",
"RequestURL": "/scan",
"RequestCommand": "C:/RR/api-compliance.ps1" }
snippet from the above script (api-compliance.ps1) ;
###############
# Setup Creds #
###############
$userID = "****"
$Pass = "*****"
#$Creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userID,$Pass
$vCenter = "vCenter01"
$cluster = "Cluster01"
$vmhost = "Host01"
$bl = "Baseline01"
######################
# Connect to vCenter #
######################
Connect-VIServer $VCTRs -user $userID -password $Pass -WarningAction SilentlyContinue -Force
$baseline = Get-Baseline | ? {$_.name -eq $bl}
$baseline | Attach-Baseline -Entity $vmhost -Confirm:$false
Scan-Inventory -Entity $vmhost
Right now we are hardcoding the below values
$vCenter = "vCenter01"
$cluster = "Cluster01"
$vmhost = "Host01"
But we want these to be passed as a request body. Can someone help?
Simply declare parameters $RequestArgs and $Body in the target script/function, and RestPS will automatically pass the appropriate values along as strings:
param(
[string]$RequestArgs,
[string]$Body
)
$RequestArgs.Split('&') |ForEach-Object {
$paramName,$paramValue = $_.Split('=')
Write-Host "Received query parameter ${paramName} with value '$paramValue'"
}
I am trying to create an auto shutdown policy with Powershell for my Azure VM, but keep running into this error:
New-AzureRmResource : MissingRequiredProperty : Missing required property TargetResourceId.
At C:\Users\home\Documents\CreateAzureVM.ps1:167 char:1
+ New-AzureRmResource -Location $Loc -ResourceId $ScheduledShutdownReso ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureRmResource], ErrorResponseMessageException
+ FullyQualifiedErrorId : MissingRequiredProperty,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceCmdlet
I am at a lost on how to fix this error, this is my script piece so far:
$SubscriptionId = $AzContext.Context.Subscription.Id;
$VMResourceId = (Get-AzureRmVM).id
$ScheduledShutdownResourceId = "/subscriptions/$SubscriptionId/resourceGroups/$RSGName/providers/microsoft.devtestlab/schedules/shutdown-computevm-$VMName"
$Properties = #{}
$Properties.Add('status', 'Enabled')
$Properties.Add('taskType', 'ComputeVmShutdownTask')
$Properties.Add('dailyRecurrence', #{'time'= 1159})
$Properties.Add('timeZoneId', "Eastern Standard Time")
$Properties.Add('notificationSettings', #{status='Disabled'; timeInMinutes=15})
$Properties.Add('targetResourceId', $VMResourceId)
#Error
New-AzureRmResource -Location $Loc -ResourceId $ScheduledShutdownResourceId -Properties $Properties -Force
The cause:
This script $VMResourceId = (Get-AzureRmVM).id is not for a specific VM. You should get a specific VM.
Try to use following Powershell scripts:
$SubscriptionId = $AzContext.Context.Subscription.Id
$VM = Get-AzureRmVM -ResourceGroupName $RGName -Name VMName
$VMResourceId = $VM.Id
$ScheduledShutdownResourceId = "/subscriptions/$SubscriptionId/resourceGroups/wayneVMRG/providers/microsoft.devtestlab/schedules/shutdown-computevm-$VMName"
$Properties = #{}
$Properties.Add('status', 'Enabled')
$Properties.Add('taskType', 'ComputeVmShutdownTask')
$Properties.Add('dailyRecurrence', #{'time'= 1159})
$Properties.Add('timeZoneId', "Eastern Standard Time")
$Properties.Add('notificationSettings', #{status='Disabled'; timeInMinutes=15})
$Properties.Add('targetResourceId', $VMResourceId)
#Error
New-AzureRmResource -Location eastus -ResourceId $ScheduledShutdownResourceId -Properties $Properties -Force
Here is the result:
here a loop to read the current configured value for Auto-shutdown of AZ vms (can easy add update/change/set based on Wayne Yang example above)
Example will loop thru many subscription.
:
###################
##:List all subs which are enabled
#$AllSubID = (Get-AzureRmSubscription | Where {$_.State -eq "enabled"}).SubscriptionId
### above might not work depends on account, just get all below.
$AllSubID = (Get-AzureRmSubscription).SubscriptionId
Write-Output "$(Get-Date -format s) :: List of Subscription below"
$AllSubID
$AllVMList = #()
Foreach ($SubID in $AllSubID) {
Select-AzureRmSubscription -Subscriptionid "$SubID"
##list all VMs
$VMs = Get-AzureRmVM
Foreach ($VM in $VMs) {
$VM = New-Object psobject -Property #{`
"Subscriptionid" = $SubID;
"ResourceGroupName" = $VM.ResourceGroupName;
"VMName" = $VM.Name}
$AllVMList += $VM | select Subscriptionid,ResourceGroupName,VMName
}
}
$AllVMList
## Get AutoShutdown info
Foreach ($VM in $AllVMList) {
Write-Output "$(Get-Date -format s) :: VM: $($VM.VMName) :: $($VM.ResourceGroupName) :: $($VM.Subscriptionid)"
$ScheduledShutdownResourceId = "/subscriptions/$($VM.Subscriptionid)/resourceGroups/$($VM.ResourceGroupName)/providers/microsoft.devtestlab/schedules/shutdown-computevm-$($VM.VMName)"
## Write-Output "$ScheduledShutdownResourceId"
$VMShutdownInfo = get-AzureRmResource -ResourceId $ScheduledShutdownResourceId
Write-Output "$(Get-Date -format s) :: VM: $($VM.VMName) :: status: $($VMShutdownInfo.properties.status) ; taskType: $($VMShutdownInfo.properties.taskType) ; timeZoneId: $($VMShutdownInfo.properties.timeZoneId) ; dailyRecurrence: $($VMShutdownInfo.properties.dailyRecurrence) ; "
}
###Done
I'm trying to create a DSC script that can be run locally on a machine that is to be a Read Only Domain Controller. The xActiveDirectory DSC resource doesn't provide for creating an RODC so I have to use a script resource and use Install-ADDSDomainController.
My problem arises when I have to provide the Safe Mode Administrator Password. The parameter will only accept a SecureString, however I'm having trouble passing through the secure string to the DSC configuration. I can pass through a PSCredential object for the Credential parameter but the Safe Mode parameter won't accept it so I need a separate variable. I am encrypting the credentials with a self signed cert which seems to be working ok at this point.
My DSC code, there are a couple of commented out lines at the bottom where I tested alternate ways of creating the secure string non of which worked:
get-childitem cert:\localmachine\my | where-object {$_.Subject -like "*CN=DscEncryptionCert*"} | remove-item
$cert = New-SelfSignedCertificate -Type DocumentEncryptionCertLegacyCsp -DnsName 'DscEncryptionCert' -HashAlgorithm SHA256
$cert | Export-Certificate -FilePath "c:\RODC\DscPublicKey.cer" -Force
$thumbprint = (get-childitem cert:\localmachine\my | where-object {$_.Subject -like "*CN=DscEncryptionCert*"}).Thumbprint
$ConfigData= #{
AllNodes = #(
#{
NodeName = "localhost"
CertificateFile = "C:\RODC\localhost.cer"
Thumbprint = $thumbprint
};
);
}
configuration RODC
{
param(
[Parameter()]$DomainName,
[Parameter()]$ReplicationSourceDC,
[Parameter()]$SiteName,
[Parameter()]$Thumbprint,
[PSCredential]$PSCredential = $PSCredential,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.Security.SecureString]$safemodepassword = $safemodepassword
)
Import-DscResource -module 'PSDesiredStateConfiguration'
Node localhost
{
LocalConfigurationManager
{
CertificateId = $Thumbprint
}
WindowsFeature ADDSInstall
{
Ensure = 'Present'
Name = 'AD-Domain-Services'
IncludeAllSubFeature = $true
}
script installRODC
{
DependsOn = '[WindowsFeature]ADDSInstall'
SetScript =
{
Import-Module ADDSDeployment
Install-ADDSDomainController `
-AllowPasswordReplicationAccountName #("test\Allowed RODC Password Replication Group") `
-NoGlobalCatalog:$false `
-Credential:$PSCredential `
-CriticalReplicationOnly:$false `
-DenyPasswordReplicationAccountName #("BUILTIN\Administrators", "BUILTIN\Server Operators", "BUILTIN\Backup Operators", "BUILTIN\Account Operators", "test\Denied RODC Password Replication Group") `
-DomainName:$using:DomainName `
-InstallDns:$true `
-NoRebootOnCompletion:$false `
-ReadOnlyReplica:$true `
-ReplicationSourceDC:$using:ReplicationSourceDC `
-SiteName $using:SiteName `
-Force:$true `
-SafeModeAdministratorPassword:$safemodepassword
}
TestScript =
{
if((get-wmiobject win32_computersystem).domainrole -eq 4){$true}else{$false}
}
GetScript =
{
Return #{result = (get-wmiobject win32_computersystem).domainrole}
}
}
}
}
$PSCredential = Get-Credential
$safemodepassword = Read-Host -assecurestring "Please enter the Safe Mode Administrator password"
#$safemodepassword = ConvertTo-SecureString "P#55word" -AsPlainText -Force
#$safemodepassword = New-Object System.Management.Automation.PSCredential ("Administrator", $password)
RODC -DomainName test.local -ReplicationSourceDC DC1.test.local -Sitename Site11 -PSCredential $PSCredential -safemodepassword $safemodepassword
Set-DscLocalConfigurationManager -path .\RODC -Verbose -Force
Start-DscConfiguration -path .\RODC -Verbose -force
A simple test I wrote to check if the script code itself is working, which it is:
$PSCredential = Get-Credential
$safemodepassword = Read-Host -assecurestring "Please enter the Safe Mode Administrator password"
$DomainName = "test.local"
$ReplicationSourceDC = "DC1.test.local"
$Sitename = "Site11"
Install-ADDSDomainController `
-AllowPasswordReplicationAccountName #("test\Allowed RODC Password Replication Group") `
-NoGlobalCatalog:$false `
-Credential:$PSCredential `
-CriticalReplicationOnly:$false `
-DenyPasswordReplicationAccountName #("BUILTIN\Administrators", "BUILTIN\Server Operators", "BUILTIN\Backup Operators", "BUILTIN\Account Operators", "test\Denied RODC Password Replication Group") `
-DomainName:$DomainName `
-InstallDns:$true `
-NoRebootOnCompletion:$false `
-ReadOnlyReplica:$true `
-ReplicationSourceDC:$ReplicationSourceDC `
-SiteName $SiteName `
-Force:$true `
-SafeModeAdministratorPassword:$safemodepassword
The main error I get is:
PowerShell DSC resource MSFT_ScriptResource failed to execute
Set-TargetResource functionality with error message: Cannot bind
parameter 'SafeModeAdministratorPassword' to the target. Exception
setting "SafeModeAdministratorPassword":
"SafeModeAdministratorPassword cannot be null."
Is it NULL because it's not being passed through correctly? If I print out the value of the variable it tells me there is a secure string present but that doesn't seem to be the case in the actual DSC configuration itself.
If I change -SafeModeAdministratorPassword:$safemodepassword to include $using as I have with some of the other variables I get the error:
PowerShell DSC resource MSFT_ScriptResource failed to execute
Set-TargetResource functionality with error message: Exception calling
"Deserialize" with "1" argument(s): "The system cannot find the path
specified.
I'm not sure where I can go from here. Any help would be appreciated. Thanks.
I think it's not possible to pass SecureString inside Script block.
It's encrypted by key which exists on local PC only.
PS C:\> [System.Management.Automation.PSSerializer]::Deserialize('<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
>> <Obj RefId="0">
>> <TN RefId="0">
>> <T>System.Management.Automation.PSCredential</T>
>> <T>System.Object</T>
>> </TN>
>> <ToString>System.Management.Automation.PSCredential</ToString>
>> <Props>
>> <S N="UserName">Hey</S>
>> <SS N="Password">01000000d08c9ddf0115d1118c7a00c04fc297eb0100000034646a6e6b53d244b223386a302a6fe700000000020000000000106600000001000020000000db75ebc7ae7b02d84ef6cb1161559006bdd81a84ccd5d152f3a6fdfdcf102165000000000e8000000002000020000000f0c4f2676ae5a65d2823ec8d73c352c79a97d7fd3971fd64c084d90c6c94ff7c20000000476fd1bd7f1842fdfb2e2f2fc4fd17ee0d7b41fefb39cda407bd2a6176e7b40e40000000575dac900276dcc550f09fe48b341885431dd8d287a6073ccbbfbc89e2ff8ee9e3158a8d75a52332ab2a60126cbc69232c6d9109d1db17e28535726b5e1ec2b3</SS>
>> </Props>
>> </Obj>
>> </Objs>')
UserName Password
-------- --------
Hey System.Security.SecureString
[WIN-U42BH7N5O4B]: PS C:\> [System.Management.Automation.PSSerializer]::Deserialize('<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
>> <Obj RefId="0">
>> <TN RefId="0">
>> <T>System.Management.Automation.PSCredential</T>
>> <T>System.Object</T>
>> </TN>
>> <ToString>System.Management.Automation.PSCredential</ToString>
>> <Props>
>> <S N="UserName">Hey</S>
>> <SS N="Password">01000000d08c9ddf0115d1118c7a00c04fc297eb0100000034646a6e6b53d244b223386a302a6fe700000000020000000000106600000001000020000000db75ebc7ae7b02d84ef6cb1161559006bdd81a84ccd5d152f3a6fdfdcf102165000000000e8000000002000020000000f0c4f2676ae5a65d2823ec8d73c352c79a97d7fd3971fd64c084d90c6c94ff7c20000000476fd1bd7f1842fdfb2e2f2fc4fd17ee0d7b41fefb39cda407bd2a6176e7b40e40000000575dac900276dcc550f09fe48b341885431dd8d287a6073ccbbfbc89e2ff8ee9e3158a8d75a52332ab2a60126cbc69232c6d9109d1db17e28535726b5e1ec2b3</SS>
>> </Props>
>> </Obj>
>> </Objs>')
Exception calling "Deserialize" with "1" argument(s): "Key not valid for use in specified state.
"
At line:1 char:1
+ [System.Management.Automation.PSSerializer]::Deserialize('<Objs Versi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CryptographicException
Use Cryptographic Message Syntax encrypted strings.
Configuration WebSitePublishConfig
{
param
(
[Parameter(Mandatory=$true)]
[PSCredential] $Credential,
[Parameter(Mandatory=$true)]
[string] $CertificateFile
)
Import-DscResource -ModuleName PSDesiredStateConfiguration
$UserName = $Credential.UserName
$EncryptedPassword = $Credential.GetNetworkCredential().Password | Protect-CmsMessage -To $CertificateFile
Script MyScript
{
SetScript = `
{
# $using:UserName
$password = Unprotect-CmsMessage -Content $using:EncryptedPassword
}
}
}
If you don't care about security, pass password in plain text:
$UserName = $Credential.UserName
$PasswordPlain = $Credential.GetNetworkCredential().Password
Script MyScript
{
SetScript = `
{
# $using.UserName
# $using:PasswordPlain
}
}