Azure Pipelines reading JSON into variables with a 6 liner — ready to parse terraform output.
We are using terraform to build our cloud environments and needed to parse the output from it.
How to parse a json file to variables in azure pipelines with PowerShell 7 on linux and on windows.
Line 1 — Reads a JSON file into a HashTable
Line 2 — Starts a loop — which is running for each key and value of the table
Line 3 — Grabs the variable name. Having such an Json { “age”:3} it would be age
Line 4 — Grabs the value, of the Json. In this case I’m using the nested value.
This line is a bit tricky:
If you don’t have any nested properties (again { “age”:3}) then this would be: $_.value
If you have nested properties like in terraform outputs then this is $_.value[“value”] — where the [“value”] is the nested path of your json.
Which means it could be $_.value[“type”], or $_.value[“sensitive”] as well. Or you could use $_.value.value, $_.value.type, $_.value.sensitive as well.
Line 5 sets the variable within your pipeline. In this case all variables from the json will be prefixed with “Terraform_”.
Using the “Terraform” — Output Json. The script would generate the following variable(s):
Terraform_SecretOutput = “A terraform secret”
Here is how I combine terraform and the variable parsing:
Additional readings:
How to manage variables in scripts in azure pipelines: https://docs.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#set-variables-in-scripts
Hashtables in Powershell: https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-hashtable?view=powershell-7.1
Running Terraform in azure pipelines: https://azuredevopslabs.com//labs/vstsextend/terraform/