How to reference the label value in k8s yaml file

2/12/2019

I want to reference the label's value in VirtualService's spec section inside k8s yaml file. I use ${metadata.labels[component]} to indicate the positions below. Is there a way to implement my idea?

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: istio-ingress-version
  namespace: netops
  labels:
    component: version
spec:
  hosts:
  - "service.api.com" 
  gateways:
  - public-inbound-gateway 
  http:
  - match: 
    - uri:
        prefix: /${metadata.labels[component]}/
      headers: 
        referer:
          regex: ^https://[^\s/]*a.api.com[^\s]* 
    rewrite:
      uri: "/"
    route:
    - destination:
        host: ${metadata.labels[component]}.3da.svc.cluster.local  
  - match: 
    - uri:
        prefix: /${metadata.labels[component]}/
      headers: 
        referer:
          regex: ^https://[^\s/]*b.api.com[^\s]* 
    rewrite:
      uri: "/"
    route:
    - destination:
        host: ${metadata.labels[component]}.3db.svc.cluster.local  
  - match: 
    - uri:
        prefix: /${metadata.labels[component]}/
    rewrite:
      uri: "/"
    route:
    - destination:
        host: ${metadata.labels[component]}.3db.svc.cluster.local
-- Jeffrey
istio
kubernetes
yaml

2 Answers

2/12/2019

This isn't a capability of Kubernetes itself, however other tools exist that can help you with this scenario.

The main one of these is Helm. It allows you to create variables that can be shared across several different YAML files, allowing you to share values or even fully parameterise your deployment.

-- Paul Annetts
Source: StackOverflow

2/12/2019

Look at downwardAPI to inject pod metadata like labels and annotations to pods at runtime.

apiVersion: v1
kind: Pod
metadata:
  name: kubernetes-downwardapi-volume-example
  labels:
    zone: us-est-coast
    cluster: test-cluster1
    rack: rack-22
  annotations:
    build: two
    builder: john-doe
spec:
  containers:
    - name: client-container
      image: gcr.io/google_containers/busybox
      command: ["sh", "-c", "while true; do if [[ -e /etc/labels ]]; then cat /etc/labels; fi; if [[ -e /etc/annotations ]]; then cat /etc/annotations; fi; sleep 5; done"]
      volumeMounts:
        - name: podinfo
          mountPath: /etc
          readOnly: false
  volumes:
    - name: podinfo
      downwardAPI:
        items:
          - path: "labels"
            fieldRef:
              fieldPath: metadata.labels
          - path: "annotations"
            fieldRef:
              fieldPath: metadata.annotations
-- P Ekambaram
Source: StackOverflow