P i
P i

Reputation: 30784

Bizarre behaviour from piping input into `kubectl`

I am trying to substitute environment variables into a .yaml file, and pass the resulting file into kubectl:

> cat template.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: $K8S_NAMESPACE

> cat .env
K8S_NAMESPACE=leafsheets-staging-pi

> ( set -a; source .env;  envsubst < template.yaml | kubectl apply -f - )
error: You must be logged in to the server (the server has asked for the client to provide credentials)

Why this error?

I got the syntax from https://skofgar.ch/dev/2020/08/how-to-quickly-replace-environment-variables-in-a-file/

Debugging

kubectl works fine like this:

> cat pure.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: leafsheets-staging-pi

> kubectl apply -f pure.yaml 
namespace/leafsheets-staging-pi created

> kubectl apply -f pure.yaml 
namespace/leafsheets-staging-pi unchanged

And the substitution is working correctly:

> envsubst < template.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: leafsheets-staging-pi

(This is identical to pure.yaml)

But the command fails:

> ( set -a; source .env;  envsubst < template.yaml | kubectl apply -f - )
error: You must be logged in to the server (the server has asked for the client to provide credentials)

And now the original direct command (which worked before) also fails:

> kubectl apply -f pure.yaml 
error: You must be logged in to the server (the server has asked for the client to provide credentials)

Creating a fresh shell, it will work again.

Can anyone explain this bizarre behaviour? Is it a bash issue or a kubectl issue receiving stdin?

Hack solution

And what is a good workaround? I'm currently doing:

> cat template.yaml | envsubst > /tmp/foo.yaml
> kubectl apply -f /tmp/foo.yaml 

... but it feels very ugly.

Upvotes: 0

Views: 365

Answers (0)

Related Questions