Use Variables with Kustomize, Part 2

I was looking at the Kustomize variable trick I did a year ago and I think I’ve learned some new tricks worth noting down.

Variables are very handy most of the times, here’s a pattern to define a variable to be used in Kustomize templates and set its value via annotations.

# base/gateway.yaml
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: wordpress-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
  - hosts:
    # the domain name will be set by the variable
    - $(DOMAIN)
    tls:
      mode: SIMPLE
      credentialName: $(CERT)
    port:
      name: https
      number: 443
      protocol: HTTPS

# base/virtual-service.yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: wordpress-vs
spec:
  gateways:
    - wordpress-gateway
  hosts:
    # same domain here so no need to repeat the domain name, also the virtual service will always match the gateway
    - $(DOMAIN)
  http:
    - route:
      - destination:
          host: wordpress

# base/config.yaml, ensure variables are enabled for Istio resources
varReference:
  - path: spec/hosts
    kind: VirtualService
  - path: spec/servers/hosts
    kind: Gateway
  - path: spec/servers/tls/credentialName
    kind: Gateway

# at last the base/kustomize.yaml which defines 2 variables: DOMAIN and CERT
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
configurations:
  - config.yaml
resources:
  - gateway.yaml
  - virtual-service.yaml
  # the content of deployment isn't given here, any valid deployment resource should do
  - deployment.yaml 
vars:
  - name: DOMAIN
    objref:
      apiVersion: apps/v1
      kind: Deployment
      name: wordpress
    fieldref:
      fieldpath: metadata.annotations.domain
  - name: CERT
    objref:
      apiVersion: apps/v1
      kind: Deployment
      name: wordpress
    fieldref:
      fieldpath: metadata.annotations.cert

# the above templates form a base Kustomize template and any Kustomize template extending the above base can have the variables set for real values
# site1/kustomize.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: wordpress-1
bases:
  - ../base

commonAnnotations:
  domain: site1.blog
  cert: site1-blog-cert

There you have it: When building the overlay template site1, variable DOMAIN will have the value of site1.blog; and CERT variable will be set to site1-blog-cert.

🙂

Leave a Reply

Your email address will not be published. Required fields are marked *