配置跨命名空间引用
跨命名空间引用让平台团队可以运营共享 Gateway、后端和 Secret,同时让应用团队 管理各自的 Route 与 Consumer。Gateway API 要求在每一道命名空间边界上显式授权,避免在一个命名空间创建资源就自动获得另一团队资源的访问权。
不同关系所需的授权如下:
| 关系 | 授权方式 |
|---|---|
| Route 引用另一命名空间的 Gateway | Gateway 监听器通过 allowedRoutes 选择 Route 所在命名空间。 |
| Route 引用另一命名空间的后端 | 后端命名空间中的 ReferenceGrant 允许该 Route 引用。 |
| Gateway 引用另一命名空间的 TLS Secret | Secret 命名空间中的 ReferenceGrant 允许该 Gateway 引用。 |
Consumer 引用另一命名空间的凭证 Secret | Secret 命名空间中的 ReferenceGrant 允许该 Consumer 引用。 |
跨命名空间流量引用通过 Gateway API 资源支持;Ingress 资源与 APISIX 路由 CRD 不支持跨命名空间流量引用。Consumer 凭证引用是 ReferenceGrant 的实现特定用法。
这些机制用于授权资源之间的关系,并不会授予用户创建或修改这些资源的权限。配置跨命名空间引用之前,请先使用 Kubernetes RBAC 委派 Gateway API 访问权限。
前置条件
- 使用 Gateway API 资源完成设置 Ingress Controller 和网关。
- 安装此版本 Ingress Controller 支持的 Gateway API CRD。
- 使用有权创建各示例命名空间与资源的账号。
示例使用 aic 命名空间中名为 apisix 的 Gateway 和名为 apisix-config 的 GatewayProxy,这与 APISIX 设置教程创建的名称一致。
允许 Route 使用另一命名空间的后端
以下示例在 tenant-a 中创建 HTTPRoute,将它挂载到 aic 中的 Gateway,并把请求转发到 backend-ns 中的 Service:
Gateway 所有者授权来自 tenant-a 的挂载,后端所有者则单独授权访问 httpbin Service。
创建命名空间
创建租户命名空间和后端命名空间:
kubectl create namespace tenant-a
kubectl create namespace backend-ns
Kubernetes 会自动为每个命名空间添加不可变的 kubernetes.io/metadata.name 标签。Gateway 监听器将用该标签选择 tenant-a,无需自定义命名空间标 签。
创建后端服务
在后端命名空间中创建 Deployment 和 Service:
apiVersion: apps/v1
kind: Deployment
metadata:
name: httpbin
namespace: backend-ns
spec:
replicas: 1
selector:
matchLabels:
app: httpbin
template:
metadata:
labels:
app: httpbin
spec:
containers:
- name: httpbin
image: kennethreitz/httpbin
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: httpbin
namespace: backend-ns
spec:
ports:
- port: 80
targetPort: 80
protocol: TCP
selector:
app: httpbin
将配置应用到集群:
kubectl apply -f httpbin-deployment.yaml
授权后端引用
ReferenceGrant 必须创建在被引用对象所在的命名空间。请在 backend-ns 中创建以下授权,允许 tenant-a 中的 HTTPRoute 引用 httpbin Service:
apiVersion: gateway.networking.k8s.io/v1
kind: ReferenceGrant
metadata:
name: allow-httpbin-from-tenant-a
namespace: backend-ns
spec:
from:
- group: gateway.networking.k8s.io
kind: HTTPRoute
namespace: tenant-a
to:
- group: ""
kind: Service
name: httpbin
from 条目信任 tenant-a 中的 HTTPRoute;to 条目将信任限制为 ReferenceGrant 所在命名空间中的 httpbin Service。to.name 可选,但省略它会允许引用 backend-ns 中所有被匹配授权覆盖的 Service。
将配置应用到集群:
kubectl apply -f backend-referencegrant.yaml
创建路由
在租户命名空间 tenant-a 中创建 HTTPRoute,并引用 backend-ns 中的后端服务。该 HTTPRoute 会挂载到 aic 命名空间中的 apisix Gateway 资源。
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: httpbin-route
namespace: tenant-a
spec:
parentRefs:
- name: apisix
namespace: aic
rules:
- matches:
- path:
type: PathPrefix
value: /ip
backendRefs:
- kind: Service
name: httpbin
namespace: backend-ns
port: 80
weight: 1
将配置应用到集群:
kubectl apply -f httpbin-route.yaml