4

Is there a way I can pass external environment variable to kustomization.yaml from Skaffold.

Assuming i have a kustomization file below

  resources:
    - ./deployment.yaml
    - ./service.yaml

  images:
    - name: abc
      newName: <external environment>
      newTag: <external environment>

I have environment exported with Image name and tag and would like to pass into the kustomization.yaml when executing skaffold deploy or dev

Is there a way to do this or if any solution or workaround to pass an external environment variable into kustomization.yaml ?

I know i can actually use kustomize edit set image but is ugly because i need to get the old image name to set which I try to avoid. I wanted a simpler solution. I couldn't find any where that says kustomize can use environtment variable from system like docker-compose that uses ${VAR} or skaffold that uses {{.VAR}} when trying to access system environment variable

jlim
  • 909
  • 2
  • 12
  • 24

1 Answers1

2

basically, Kustomize is able to parse/replace environmental variables only in places where it is designed to. it is not a "system wide" feature and as far as i know it works only for config map generators. Said that there is a workaround

if for example you have you kustomization.yaml in /overlays/staging folder

  resources:
    - ./deployment.yaml
    - ./service.yaml

  images:
    - name: abc
      newName: $IMAGE_NAME
      newTag: $IMAGE_TAG

you can, from bash

export $IMAGE_NAME=my-app-image
export $IMAGE_TAG=latest
kubectl kustomize overlays/staging | envsubst | kubectl apply -f -

or equivalent oneliner.

The trick is to use kubectl kustomize to generate the full kustomization (which still include the variable names not valorized), it will output on stdout and pipe it in envsubst which will replace every previously exported variable in the text piped in, then pipe out again to kubectl apply -f, which this time will apply it with the trailing - (wich will make it read the yaml from stdin)

Mosè Bottacini
  • 4,016
  • 2
  • 24
  • 28
  • Thank you. I'm aware of this solution after asking from stackoverflow. Thanks for answering this. I remember back in my days when testing `envsubst`, the standard binary that comes with the OS does not support default value, example, `${IMAGE_NAME:-somename}`. The following enchanced `envsubst` does support default value `https://github.com/a8m/envsubst` . – jlim Jul 30 '21 at 17:19