Reputation: 99
I am trying to dynamically fetch list of VMs from azure using external data source and display VM individually.
Below is powershell script
$rgroup = [Console]::In.ReadLine()
$json = ConvertFrom-Json $rgroup
$name = $json.rg
$vm=Get-AzVM -ResourceGroupName $name | select name | convertTo-json
Write-Output "$vm"
Main.tf
variable "resourcegroup" {}
data "external" "test" {
program = ["Powershell.exe", "./vm.ps1"]
query = {
rg = "${var.resourcegroup}"
}}
output "value" {
value = "${data.external.test.result}"}
However, I am getting an error " command "Powershell.exe" produced invalid JSON: json: cannot unmarshal number into Go value of type map[string]string"
Can someone tel me how to loop through list of VMs and display it individually ?
-------------Edited------------
Powershell Script
$rgroup = [Console]::In.ReadLine()
$json = ConvertFrom-Json $rgroup
$name = $json.rg
$vms=(Get-AzVM -ResourceGroupName $name ).name
foreach ($vm in $vms){
$vmname= $vm |convertTo-json
Write-Output "{""Name"" : $vmname}"}
Main.tf
output "value" {
value = "${data.external.powershell_test.result.Name}"}
Powershell output
Upvotes: 1
Views: 1557
Reputation: 31414
For your issue, as victor said, Terraform data "external" can only handle flat maps of a JSON module.
With your update, when you output them in the loop, they are not JSON module, just multiple JSON modules, so it also does not match the input of the Terraform data "external".
You can create a JSON module and add the VM names to it. Change your PowerShell script like this:
$rgroup = [Console]::In.ReadLine()
$json = ConvertFrom-Json $rgroup
$name = $json.rg
$vmlist=(Get-AzVM -ResourceGroupName $name).Name
$vmNames=@{}
for($i=0; $i -lt $vmlist.Length; $i++) {
$vmNames["Name$i"] = $vmlist[$i]
}
$vmNames | ConvertTo-Json
Upvotes: 2
Reputation: 2175
data "external" can only handle flat maps, a JSON doc with nested objects will make it fail. You might want to pre-process your Powershell output.
Upvotes: 2