Home > database >  how to remove the braces and quotes from output value in terraform
how to remove the braces and quotes from output value in terraform

Time:12-03

I need to remove the quotes from the output value in terraform. The output that results is in array format, need to get only the values within the array and export it to a csv

Below is  my code
    
    data "azurerm_resources" "spokes" {
      type = "Microsoft.Network/virtualNetworks"
    }
    
    locals {
      vnetnames = ([for vnets in lookup(data.azurerm_resources.spokes, "resources", []) : lookup(vnets, "name")])
    }
    
    output "localvar" {
      value = local.vnetnames
    }
   **Actual Output**
   localvar = [
     "net1",
     "net2"
     "net3"
     "net4",
   ]
   
   **Expected Output**
     net1
     net2
     net3
     net4
   
   
   This is because I need the send the values alone to a separate file

CodePudding user response:

The main output value rendering in the terraform apply UI and in terraform output with no options is intended for human rather than machine consumption, and so it uses a syntax intended to be similar to the Terraform language syntax in the hope of it being familiar and thus easier to understand.

If you want to retrieve that data in a machine-readable format then after terraform apply is finished you can use terraform output with either the -json or -raw options to get two different kinds of raw output.

The -json option is the most general and will produce a JSON representation of any value you can write in Terraform, with a similar set of mapping rules as for the jsonencode function.

The -raw function is exclusively for strings and values that can convert automatically to strings (that is, any value that the tostring function would accept).

Your output value here seems to have a list or tuple type, and so isn't directly compatible with -raw. That means you have to main options on how to proceed:

  • Use terraform output -json localvar and then use some other software to parse the JSON and produce the newline-separated raw form you showed here. For example, you may be able to achieve that second transformation step using jq.

  • Change the output value to instead produce a string with the formatting you want, and then use terraform output -raw localvar to get the value of that string directly. It seems like you just want the direct strings separated by newlines, in which case the following expression could achieve that:

      value = join("\n", local.vnetnames)
    
  • Related