0
votes

This is the main.tf section

data "external" "extDateTime" {program = ["Powershell.exe", "${path.module}/getDateTime.ps1"] }

output "value" {value = "${data.external.extDateTime.result.dateTime}" }

This is the Powershell file getDateTime.ps1 code section

$DateTime = Get-Date -Format "yyyyMMddHHmmss"
 `Write-Output "{""dateTime"": $DateTime}"`

Then I run the following command: terraform plan

Error: Unexpected External Program Results with data.external.extDateTime, on main.tf line 26, in data "external" "extDateTime": 26: program = ["Powershell.exe", "${path.module}/getDateTime.ps1"] The data source received unexpected results after executing the program. Program output must be a JSON encoded map of string keys and string values. Program: C:\WINDOWS\System32\WindowsPowerShell\v1.0\Powershell.exe Result Error: invalid character '{' after top-level value

My understanding is the PS script has to return in JSON format but I keep getting the Result Error. Any ideas would be appreciated.

1

1 Answers

0
votes

Ensure that the JSON values are correctly formatted as strings (using back ticks to escape double quotes):

$DateTime = Get-Date -Format "yyyyMMddHHmmss"
Write-Output "{`"dateTime`": `"$DateTime`"}"

As per the Terraform docs for the external data source:

The JSON object contains the contents of the query argument and its values will always be strings.

Another way that this can be done is to create a PowerShell custom object and convert it to JSON:

$DateTime = Get-Date -Format "yyyyMMddHHmmss"
$myObject = [PSCustomObject]@{
  dateTime     = $DateTime
}
ConvertTo-Json $myObject

If you need the output to be a number, you can use the tonumber() function:

output "value" {
  value = tonumber(data.external.extDateTime.result.dateTime)
}