Search code examples
jsonterraformhashicorp-vaultterraform0.12+hashicorp

Parsing Terraform json output


I have a running vault server, I enabled transit secret engine and created a vault transit secret backend_key through terraform.

resource "vault_mount" "transit" {
  path = "transit"
  type = "transit"
}


resource "vault_transit_secret_backend_key" "transit_key" {
  backend = vault_mount.transit.path
  name    = "test-pagination-key"
  type    = "chacha20-poly1305"
}

Now I am making a curl request to fetch the generated backend key in plaintext format

data "curl_request" "transit_curl" {
  uri         = "http://vault:8200/v1/transit/datakey/plaintext/test-pagination-key/"
  http_method = "POST"

}

output "transit_response" {
  value = {
    status_code = data.curl_request.transit_curl.response_status_code
    body        = jsondecode(data.curl_request.transit_curl.response_body)
  }
}

I am able to get terraform output, but I would like to parse the output to get required value

  ~ transit_response = {
      ~ body        = {
          - auth           = null -> null
          - data           = {
              - ciphertext  = "vault:v1:ockH4Bzjzv4s4QM0ok1XqSNpA5fINiqZmIf8K9JND9urvfFRmmpFMsPX4zL4TZL1TpW3mM1J0YtNgmmk"
              - key_version = 1
              - plaintext   = "HTPoZv4gIcnXRIdZW9NiHds9+TGc+Y5uNfp+bR0QhMg="
            } -> null
          + errors         = [
              + <<-EOT
                    1 error occurred:
                        * unsupported path
                    
                EOT,
            ]
          - lease_duration = 0 -> null
          - lease_id       = "" -> null
          - renewable      = false -> null
          - request_id     = "a66b7136-58be-bfa1-452e-800d35451627" -> null
          - warnings       = null -> null
          - wrap_info      = null -> null
        }
      ~ status_code = 200 -> 404
    }

From the above terraform output, I wish to parse it and fetch only plaintext data as below

"plaintext   = "HTPoZv4gIcnXRIdZW9NiHds9+TGc+Y5uNfp+bR0QhMg=" 

How can I parse the terraform output and store it in some variable????


Solution

  • I am slightly confused here because it sounds as if you are asking how to parse a TF/HCL2 object, but based on the information provided in the question it also seems as if you are already very familiar with that syntax. Nevertheless, this is the syntax for parsing the object to achieve what you desire here:

    output "transit_response" {
      value = {
        status_code = data.curl_request.transit_curl.response_status_code
        body        = jsondecode(data.curl_request.transit_curl.response_body)
        key         = jsondecode(data.curl_request.transit_curl.response_body)["data"]["plaintext"]
      }
    }
    

    The provider resource should also really be renamed from vault_transit_secret_backend_key to vault_transit_secret_backend_keyring, but that is a whole other topic.