Convert terraform.tfvar file into json

Hi All,

I am new to terraform. Need your help please.

The below mention is the script for terraform.tfvar

vmdetail = [
{
resource_group = “abc”
instName = “vmtest”
location = “EAST US”
vnet = “abc-vnet”
subnet = “default”
OS_Type = “Linux”
instVMSize = “Standard_D2s_v3”
publisher = “RedHat”
offer = “RHEL”
sku = “7-LVM”
ver = “latest”
instOSDiskSize = “256”
instOSDiskType = “Standard_LRS”
ddiskType = “Premium_LRS”
instdDisk = “256”
Asset_ID = “1234”
domain_name = “abc”
SDC_system_catalogue = “na”
Server_purpose = “na”
IP_address = “x.x.x.x”
Tags = { cost_center = “”, environment_type = “” }
},

I want to create a json file where i can get these details from terraform.tfvar. Please let me know how to proceed. I have read most of the terraform docs but not able to find exactly how this can be covert to json.

I don’t know of any nice way to do this.

I think this should work:

terraform console <<<'jsonencode(var.vmdetail)' | jq -r .

However it relies on terraform console which is intended for interactive debugging, so I’m not sure it can be relied upon as a stable API.

Without knowing more about your use case here, I can’t be sure what the right approach is. Can you share what you want to do with the JSON generated from your tfvars file?

maxb’s console and jsonencode() idea above is neat, and you may also find my tfvars-json utility helpful.

Hi,

Thankyou for your response.

I am provisioning VM in azure as input parameter in csv file. After completing vm provisioning terraform.tfvar file is created by default. I want terraform.tfvar file to be converted to json. So that i am able to see the output in json file.

Like above i mention the terraform.tfvar file is the same output i want in the json file.

Hi,

Thankyou for your response.

I have run this command but it is giving jq command not found.

Please find the error below.

j:~/workspace/VM_Provisioning$ terraform console <<<‘jsonencode(var.vmdetail)’ | jq -r .
bash: jq: command not found

│ Error: Reference to undeclared input variable

│ on line 1:
│ (source code not available)

│ An input variable with the name “vmdetail” has not been declared. This variable can be declared with a variable “vmdetail”
│ {} block.