Passing data from powershell scripts to Terraform

I have a powershell scripts like this :

#collecting user input for client_id, client_secret, subscription_id, and tenant_id
$client_id = Read-Host -Prompt ‘Input your Azure client_id’
$client_secret = Read-Host -Prompt ‘Input your Azure client_secret’
$subscription_id = Read-Host -Prompt ‘Input your Azure subscription_id’
$tenant_id = Read-Host -Prompt ‘Input your Azure tenant_id’

I want to pass the variables $client_id, $client_secret, $subscription_id. Using data “external”.

How can i pass these data to Terraform

Hi @raphaeljuwe!

I’m not very familiar with PowerShell myself so I can’t show any concrete examples, but I can say that the key requirement for the external provider is that the program it’s running must read the data from its input and parse it as JSON, and then print JSON to its output as the result. In both cases, the JSON data will be a JSON object with all properties mapping to strings.

It looks like PowerShell has ConvertFrom-Json and ConvertTo-Json cmdlets which could help with the necessary parsing and serializing, leaving you to then implement whatever logic you need in between.

After reading what Read-Host does I think you won’t be able to use that in the external context because it requires that the PowerShell script be running in console, but the external data source will run it in the background. Instead, you’ll need to change the script to expect values to arrive via the input. After some searching I concluded that something like this might work, but again I’m not knowledgeable with PowerShell so I’m not sure this is totally correct:

$query = $input | Out-String | ConvertFrom-Json

$query would then, I think, be a powershell representation of whatever values you put in the query argument of the external data source, and so you could pass in the values you indicated in your question:

data "azurerm_client_config" "current" {}

data "external" "example" {
  program = ["powershell", "example.ps1"]
  query = {
    client_id       = data.azurerm_client_config.current.client_id
    subscription_id = data.azurerm_client_config.current.subscription_id
    tenant_id       = data.azurerm_client_config.current.tenant_id
  }
}

A Terraform configuration should not generally have direct access to a credential like client_secret, so I’d recommend having your PowerShell script access that by environment variables or whatever other out-of-band strategy you are using to make those credentials available to the azurerm provider.