Variable substitution in the new kubernetes kustomize support (since 1.14.0): kubectl apply -k ./

4/23/2019

We are using kustomize for our kubernetes deployments in this way:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:${IMAGE_VERSION}
        ports:
        - containerPort: 80

and deploy this yaml substituting the variable IMAGE_VERSION with 1.7.9

kustomize build ./nginx/overlays/dev/ | sed -e 's|${IMAGE_VERSION}'"|1.7.9|g" | kubectl apply -f -

Since kubectl 1.14 supports kustomize.

now we can do something very nice like this

kubectl apply -k ./

but how to substitute the IMAGE_VERSION variable with this new command?

-- KiteUp
customization
declarative
kubectl
kubernetes
kustomize

1 Answer

4/23/2019

You have to create a kustomization.yaml file containing the customizations.

i.e:

# kustomization.yaml
bases:
- ../base
images:
  - name: nginx-pod
    newTag: 1.15
    newName: nginx-pod-2

And for the templates, you create a base folder containing the kustomization.yaml with reference to the deployment and dependencies, i.e:

# ../base/kustomization.yaml
resources:
- deployment.yaml

and

# ../base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx-pod

Run the command:

kubectl apply -k

The above command will compile the customization and generate the following yaml to be applied to the cluster:

# Modified Base Resource
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      # The image image tag has been changed for the container
      - name: nginx
        image: nginx-pod-2:1.15
-- Diego Mendes
Source: StackOverflow