Search code examples
kubernetesgo-templatesvault

Vault init container on k8s support for deleted secrets on kv2


I'm currently in the process of upgrading our vault from KV1 to KV2. We use a Vault init container to retrieve secrets, and I've successfully modified the configuration to support both KV1 and KV2.

Here's the working configuration:

{{- range secrets "secret/${element(split("_", secret), 0)}" }}
  {{- if  eq . "${join("_", slice(split("_", secret), 1, length(split("_", secret))))}" }}
    {{- with secret "secret/${element(split("_", secret), 0)}/${join("_", slice(split("_", secret), 1, length(split("_", secret))))}" }}
      {{- if index .Data "data" }}
        {{- range $k, $v := .Data.data }}
          export ${secret}_{{ $k }}='{{ $v }}'
          export ${upper(secret)}_{{ $k | toUpper }}='{{ $v }}'
        {{- end }}
      {{- else }}
        {{- range $k, $v := .Data }}
          export ${secret}_{{ $k }}='{{ $v }}'
          export ${upper(secret)}_{{ $k | toUpper }}='{{ $v }}'
        {{- end }}
      {{- end }}
    {{- end }}
  {{- end }}
{{- end }}

However, I'm facing an issue with an edge case in KV2 where a secret is created and then deleted. In this scenario, the response from Vault looks like this:

{
  "request_id": "xx-xx-xx-xx-2b69fcf6f154",
  "lease_id": "",
  "lease_duration": 0,
  "renewable": false,
  "data": {
    "data": null
    },
    "metadata": {
      "version": 1
    }
  },
  "warnings": null
}

The problem is that .data.data doesn't contain any secret or structure; it returns null. I need assistance in modifying my code to gracefully handle this scenario and support it.

Any suggestions or insights would be greatly appreciated


Solution

  • It appears that the problem lies in the following line of code:

    {{- with secret "secret/${element(split("_", secret), 0)}/${join("_", slice(split("_", secret), 1, length(split("_", secret))))}" }}
    

    The issue arises from the secret function, which encounters difficulties when attempting to read a deleted secret in Vault KV2. This occurs because the secrets function continues to return the path of deleted secrets, as the metadata persists even after deletion. Consequently, the attempted access to a deleted secret results in failure.