Home > Back-end >  Bash function to get and decode kubernetes secrets
Bash function to get and decode kubernetes secrets

Time:10-06

I'm trying to code a bash function to get and decode a kubernetes secret's data in just one short command. My idea is to have something like kgsecd -n <namespace> <secret-name> <secret-data> that is just mapped to kubectl get secret -n <namespace> <secret-name> -o "jsonpath={.data.<secret-data>}" | base64 -d. I have already coded it as follows:

  kgsecd() {
    secretData="${@: -1}"
    kubectlParams=(${@:1:-1})
    echo "kubectl get secret ${kubectlParams} -o \"jsonpath={.data.$secretData}\" | base64 -d"
    kubectl get secret "${kubectlParams}" -o "jsonpath={.data.$secretData}" | base64 -d;
  }

However, I'm struggling to make it work as when I call it, it doesn't show any output in the terminal (apart from that from the echo sentence), but if I copy&paste and executed the output of the echo sentence, it works as expected. Let me show you what I mean with an example:

$> kgsecd -n my-ns my-secret secret-data
kubectl get secret -n my-ns my-secret -o "jsonpath={.data.secret-data}" | base64 -d
$>

But when I execute kubectl get secret -n my-ns my-secret -o "jsonpath={.data.secret-data}" | base64 -d, I get the expected result.

CodePudding user response:

If you are using bash try the following, only change is the way kubectlParams is assigned. Here, kubectlParams is assigned with 1st arg to penultimate($#-1) arguments.

Also, "${kubectlParams}" if quoted, then will be considered as a command. Eg: -n my-ns my-secret would be consider as as a single string. and it would be considered as a single string , and that string is argument to kubectl. kubectl understand -n , my-ns, my-secret , but not -n my-ns mysecret.

kgsecd() {
 secretData="${@: -1}"
 kubectlParams=${@:1:$#-1}

 echo "kubectl get secret ${kubectlParams} -o \"jsonpath={.data.$secretData}\" | base64 -d"
 kubectl get secret ${kubectlParams} -o "jsonpath={.data.$secretData}" | base64 -d
}

Execution output:

#test secret created:
kubectl create secret  generic my-secret -n my-ns --from-literal=secret-data=helloooooo


#function output
kgsecd -n my-ns my-secret secret-data
kubectl get secret -n my-ns my-secret -o "jsonpath={.data.secret-data}" | base64 -d
helloooooo

#manual command execution output:

kubectl get secret -n my-ns my-secret -o "jsonpath={.data.secret-data}" | base64 -d
helloooooo

zsh solution(see comments by OP):

kgsecd() { kubectl get secret ${@:1:-1} -o "jsonpath={.data.${@: -1}}" | base64 -d }
  • Related