Unable to fetch data using external data source

I am trying to fetch values from azure using external data source in terraform. However, i dont understand what am i doing wrong when i try to export values using write-output, getting an error

data.external.powershell_test: data.external.powershell_test: command "Powershell.exe" produced invalid JSON: invalid character 'l' looking for beginning of object key string"

Below is my script

$vm=(Get-AzureRmVM -ResourceGroupName MFA-RG -Name vm2).name | convertTo-json
Write-Output "{""first"" : ""$vm""}"

Main.tf file

data "external" "powershell_test" {
  program = ["Powershell.exe", "./vm.ps1"]
}

output "value" {
  value = "${data.external.powershell_test.result.first}"
}

Can someone tel me what wrong with the script ? and if i am using write-out properly ?

Edited-------------

Below is the screenshot when i run vm.ps1 directly enter image description here

Also, when i directly assign value to a variable as below, terraform is able to execute the code.

$vm = "testvm"
Write-Output "{""first"" : ""$vm""}"

enter image description here

728x90

2 Answers Unable to fetch data using external data source

data.external.powershell_test.result is the only valid attribute, and it is map.

So the code will be changed to

output "value" {
  value = "${data.external.powershell_test.result['first']}"
}

Reference:

https://www.terraform.io/docs/configuration-0-11/interpolation.html#user-map-variables

6 days ago

For your issue, you should change your PowerShell command like this:

$vm=(Get-AzureRmVM -ResourceGroupName MFA-RG -Name vm2).name | convertTo-json
Write-Output "{""first"" : $vm}"

And you could change the code in the data source like this or not, but I suggest you do this:

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

The result on my side is below:

enter image description here

I use the new Azure PowerShell module Az and my code shows here:

PowerShell:

$vm=(Get-AzVM -ResourceGroupName charles -Name azureUbuntu18).name | convertTo-json
Write-Output "{""first"" : $vm}"

Terraform:

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

output "value" {
  value = "${data.external.powershell_test.result.first}"
}

6 days ago