jqvault

extract ca chain that has multiple CA as list from vault using jq and format into single ca.crt file


I trying to generate certs uisng vault pki role. How can i create a single file called ca.crt from the wget command output.

$ wget --method=POST --header="X-Vault-Namespace: ns" --header="X-Vault-Token: $VAULT_TOKEN" --body-data='{"common_name": "test.example.com", "ttl": "5m"}' https://127.0.0.1:8200/v1/pki/dev/issuing_ca/issue/dev -q -O - | jq '.data.ca_chain'
Response
[
  "-----BEGIN CERTIFICATE-----\nMIIF5jCCA86W6j2PehfjWs3\nR55ogX1Z2jk/dvIIp.......Z067gh7nrDE56fzhyA=\n-----END CERTIFICATE-----",
  "-----BEGIN CERTIFICATE-----\nMIIF4DCCA8iNzdTHItwqVl1cTglr6bcry0vckey68u+.......4gR0CRtJ\nCaLcNKCBGi/jn6pekNVvgjBamsM=\n-----END CERTIFICATE-----",
  "-----BEGIN CERTIFICATE-----\nMIIFMzCCAxnNDE5MTlaFwumZ8\nHL8n10r0b35LtMT........CxSXIjAZJRE8Fh9jOIm0\n-----END CERTIFICATE-----"
]

$ cat ca.crt

-----BEGIN CERTIFICATE-----
MIIF5jCCA86W6j2PehfjWs3
.
.
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIF5jCCA86W6j2PehfjWs3
.
.
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
nMIIF4DCCA8iNzdTHItwqVl1c
.
.
-----END CERTIFICATE-----

Solution

  • You'll need to output raw (-r) and combine the array into a single output ([]).

    Don't forget an > ca.crt to actually write the output to a file.

    wget ... | jq -r '.data.ca_chain[]' > ca.crt
    

    From OP's comment, to save this in a variable before writing to a file:

    result="$(wget ... | jq -r '.data.ca_chain[]' > ca.crt)"
    echo -e "Final cert:\n $result"
    echo "$result" > ca.crt 
    

    Don't forget the quotes ("") around bash variables, those are very important in this case: