Istio EnvoyFilter to add x-request-id to all responses

In: General

17 Sep 2020

A quick snippet to add an Istio EnvoyFilter to add x-request-id to all responses

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: gateway-response
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      context: GATEWAY
      listener:
        filterChain:
          filter:
            name: "envoy.http_connection_manager"
            subFilter:
              name: "envoy.router"
    patch:
      operation: INSERT_BEFORE
      value:
       name: envoy.lua
       typed_config:
         "@type": "type.googleapis.com/envoy.config.filter.http.lua.v2.Lua"
         inlineCode: |
          function envoy_on_request(handle)
             local metadata = handle:streamInfo():dynamicMetadata()
             local headers = handle:headers()
             local rid = headers:get("x-request-id")

             -- for key, value in pairs(handle:headers()) do
             --   handle:logTrace("key:" .. key .. " <--> value:" .. value)
             -- end

             if rid ~= nil then
               metadata:set("envoy.filters.http.lua", "req.x-request-id", rid)
             end
           end

           function envoy_on_response(handle)
             local metadata = handle:streamInfo():dynamicMetadata():get("envoy.filters.http.lua")
             local rid = metadata["req.x-request-id"]
             if rid ~= nil then
               handle:headers():add("x-request-id", rid)
             end
           end

Comment Form

About this blog

I have been a developer for roughly 10 years and have worked with an extensive range of technologies. Whilst working for relatively small companies, I have worked with all aspects of the development life cycle, which has given me a broad and in-depth experience.