有没有一种方法在 Kubernetes 中在命名空间之间共享 configMap?

41
我们在开发环境和测试环境中分别使用一个命名空间。在每个命名空间中,我们拥有多个配置地图(configMaps)和密钥(secrets),但两个环境之间存在许多共享变量,因此我们希望有一个公共文件来管理这些变量。
是否有一种方法可以在默认命名空间中拥有一个基本的configMap,并使用类似以下方式引用它:
- envFrom:
    - configMapRef:
        name: default.base-config-map
如果这不可能,除了通过命名空间复制变量之外,还有其他方法吗?

我认为如果k8s支持它会很好。然而,目前还没有支持。因此,唯一的方法是在不同的NS之间创建副本。 - linehrr
我认为可以使用 https://kubernetes.io/docs/reference/access-authn-authz/rbac/ 上的示例来实现。 - Andrew
4个回答

34

Kubernetes 1.13及更早版本

它们无法共享,因为它们不能从其命名空间外的Pod访问。资源的名称必须在命名空间内唯一,但不跨越命名空间。

解决方法是将其复制过去。

在命名空间之间复制secrets
kubectl get secret <secret-name> --namespace=<source-namespace> --export -o yaml \
  | kubectl apply --namespace=<destination-namespace> -f -
在命名空间之间复制配置映射
kubectl get configmap <configmap-name>  --namespace=<source-namespace> --export -o yaml \
  | kubectl apply --namespace=<destination-namespace> -f -

Kubernetes 1.14+

在1.14版本中,--export标志已被弃用 可以使用以下命令代替:

kubectl get secret <secret-name> --namespace=<source-namespace>  -o yaml \
  | sed 's/namespace: <from-namespace>/namespace: <to-namespace>/' \
  | kubectl create -f -

如果有人仍然需要该标志,可以使用由@zoidbergwill编写的导出脚本


1
对于使用PowerShell的用户,该命令将是: kubectl get secret <secret-name> --namespace=<source-namespace>  -o yaml | % {$_.replace("namespace: <source-namespace>","namespace: <destination-namespace>")} | kubectl create -f - - Mark

1
除了接受的答案之外,如果资源(即secretconfigMaps)可能会发生变化,并且应该在命名空间之间自动同步,那么考虑使用类似Reflector的东西可能是值得的,或者如果只需要secret,可以考虑使用clustersecret来减少手动操作。
使用Reflector将涉及三个步骤:
1. 通过例如Helm chart部署Reflector。 2. 在例如生产namespace中创建一个带注释的源资源。 3. 配置Reflector以同步资源。

apiVersion: v1
kind: ConfigMap
metadata:
  name: source-resource
  namespace: production
  annotations:
    reflector.v1.k8s.emberstack.com/reflection-allowed: "true"
    reflector.v1.k8s.emberstack.com/reflection-allowed-namespaces: "testing"
data:
  ...

创建一个带有注释的镜像资源,例如在测试命名空间中,并且不包含数据。

apiVersion: v1
kind: ConfigMap
metadata:
  name: mirrored-resource
  namespace: testing
  annotations:
    reflector.v1.k8s.emberstack.com/reflects: "production/source-resource"
data:
  ...

0
您可以使用kubexns作为initContainer来完成此操作。

-3
请使用以下命令将一个命名空间中的内容复制到另一个命名空间:
kubectl get configmap -n -o yaml | sed 's/namespace: /namespace: /' | kubectl create -f -
kubectl get secret -n -o yaml | sed 's/namespace: /namespace: /' | kubectl create -f -

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接