LordBoBCUP
LordBoBCUP

Reputation: 103

Terraform list(object{}) to powershell variable using jsonencode

I am trying to pass a list of objects to a powershell script via an process level environment variable but facing issues with the encoding between terraform jsonencode & Powershell on Windows.

Using something similar to

data "template_file" "script" {
  template = file("${path.module}\\script.ps1")
  vars = {
    "tfListOfObjects" = jsonencode(var.list-of-objects)
  }
}
resource "null_resource" "example1" {
  triggers = {
    template_rendered = data.template_file.script.rendered
  }
  provisioner "local-exec" {
    command = "PowerShell -file script.ps1"
  }
}
variable "list-of-objects" {
  type = list(object({
    first_name = string
    last_name  = string
    region   = string
  }))
}

Passing in the following as the list of objects

list-of-objects = [
  {
    first_name = "User"
    last_name  = "1"
    region     = "USNE"
  },
  {
    first_name = "User"
    last_name  = "2"
    region     = "USNW"
  },
  {
    first_name = "User"
    last_name  = "3"
    region     = "EUNE"
  }
]

The script is very simple as its only for proof it works at this point,

$testObjects = "${tfListOfObjects}"

[System.Environment]::SetEnvironmentVariable('testObjects', $testObjects, [System.EnvironmentVariableTarget]::Process)


write-host "${testObjects}"
Write-Host "Does this work?" 
Write-Host "Does this work?" >> C:\Temp\terraformresult.txt
write-Host ""
write-host $env:testObjects | ConvertFrom-JSON 

So far the only output I see is in the console once I run the terraform and all I see is 'Does this work?' The other lines are blank suggesting I'm attempting to view empty variables. The only error I've been able to generate so far is below which suggests it doesn't like the escaping that terraform jsonencode is doing. Has anyone faced issues with the escaping that terraform uses and powershell on windows specifically?

char:26\r\n+ ... ounts = \"[{\"first_name\":\"User\",\"last_name\":\"1\",\"region\":\"USNE ...\r\n+
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nUnexpected token 'first_name\":\"User\",\"last_name\":\"1\",...'

Ultimately I'm expecting to be able to deconstruct the list(object{}) in powershell by using convertfrom-json and then utilize the variable throughout a script etc. The script will be passed to VM's as part of their initialization so templatefile isn't appropriate here

Upvotes: 0

Views: 570

Answers (1)

Marcin
Marcin

Reputation: 238199

I think you should use ' and $$ in the template:

$testObjects = '${tfListOfObjects}'

[System.Environment]::SetEnvironmentVariable('testObjects', $testObjects, [System.EnvironmentVariableTarget]::Process)


write-host "$${testObjects}"
Write-Host "Does this work?"
Write-Host "Does this work?" >> C:\Temp\terraformresult.txt
write-Host ""
write-host $env:testObjects | ConvertFrom-JSON

Upvotes: 1

Related Questions