您可以使用特使过滤器来做到这一点。
在 envoy 过滤器下面,向通过 istio 入口网关的所有请求添加customer-id
带有值的请求标头。alice
如果有人想使用它,我还注释了响应标头的代码。
apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
name: lua-filter
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(request_handle)
request_handle:headers():add("customer-id", "alice")
end
# function envoy_on_response(response_handle)
# response_handle:headers():add("customer-id", "alice")
# end
我曾经使用 yamls 来测试它,它可能对测试上述过滤器很有用。
- 如果您将上述过滤器与 alice 标头一起使用,则所有请求都将转到 nginx-v1
- 如果您将上述过滤器与 bob 标头一起使用,那么所有请求都会转到 nginx-v2
- 如果删除此过滤器,则 nginx-v1 和 nginx-v2 之间的比例为 50/50
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-v1
spec:
selector:
matchLabels:
run: nginx1
replicas: 1
template:
metadata:
labels:
run: nginx1
app: frontend
spec:
containers:
- name: nginx1
image: nginx
ports:
- containerPort: 80
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo Hello nginx1 > /usr/share/nginx/html/index.html"]
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-v2
spec:
selector:
matchLabels:
run: nginx2
replicas: 1
template:
metadata:
labels:
run: nginx2
app: frontend
spec:
containers:
- name: nginx2
image: nginx
ports:
- containerPort: 80
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo Hello nginx2 > /usr/share/nginx/html/index.html"]
---
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: frontend
spec:
ports:
- name: http-front
port: 80
protocol: TCP
selector:
app: frontend
---
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: gatewayx
spec:
selector:
istio: ingressgateway # use istio default controller
servers:
- port:
number: 80
name: http
protocol: HTTP
hosts:
- "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: nginxvirt
spec:
hosts:
- '*'
gateways:
- gatewayx
http:
- name: "route-1"
match:
- headers:
customer-id:
exact: alice
route:
- destination:
host: nginx
subset: v1
- name: "route-2"
match:
- headers:
customer-id:
exact: bob
route:
- destination:
host: nginx
subset: v2
- route:
- destination:
host: nginx
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: nginxdest
spec:
host: nginx
subsets:
- name: v1
labels:
run: nginx1
- name: v2
labels:
run: nginx2