skip to Main Content

I have the following json output

{
  "secrets": [
    [
      "{",
      "  "name": "testSecret",",
      "  "vault-apikey": "kv",",
      "  "vault-value": "sabrinaTest"",
      "}"
    ]
  ]
}

But I need the output to be a little cleaner and look like this:

{
  "secrets": [
    [
        {
           "name" : "testSecret",
           "vault-apikey" : "kv",
           "vault-value" : "sabrinaTest"
        }
    ]
  ]
}

These are the commands that I’m currently running to get this output:

TEST_SECRET_JSON=$(hcp vault-secrets secrets open testSecret --format=json)

SECRETS_INFO=$(echo $TEST_SECRET_JSON | jq -r '{"name": .name, "vault-apikey": .type, "vault-value": .static_version.value}')

jq -n --arg value "${SECRETS_INFO}" '{ secrets : [ $value | split("n") ] }' >> secret.json

I have tried other variations, but none have produced the desired results.

2

Answers


  1. SECRETS_INFO is already a jq object; use --argjson instead of --arg.

    $ jq -n --argjson value "${SECRETS_INFO}" '{ secrets : [ $value ] }'
    {
      "secrets": [
        {
          "name": "testSecret",
          "vault-apikey": "kv",
          "vault-value": "sabrinaTest"
        }
      ]
    }
    

    Or, just pipe the object into jq as input.

    echo "$SECRETS_INFO" | jq '{ secrets : [.] }'
    
    Login or Signup to reply.
  2. Issue is the way you are handling jq to handle the formatting. You’re splitting the JSON string into separate lines, but what you need is to parse and preserve it as an object. Here is a better approach

    1. Use jq to create the desired JSON structure directly, without splitting it to two lines.
    2. Ensure that the output from the vault-secrets command is parsed as JSON.
    TEST_SECRET_JSON=$(hcp vault-secrets secrets open testSecret --format=json)
    
    # Parse the necessary fields and construct the JSON structure
    SECRETS_INFO=$(echo $TEST_SECRET_JSON | jq -c '{"name": .name, "vault-apikey": .type, "vault-value": .static_version.value}')
    
    # Use jq to construct the final JSON
    jq -n --argjson value "$SECRETS_INFO" '{ secrets: [ [$value] ] }' >> secret.json
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search