Spring 启动应用程序不使用 k8 gke 服务帐户而是使用默认服务帐户

Spring boot application not using k8 gke service account instead using a default service account

问题陈述:

我已经在命名空间下的 gke 中部署了一个 spring 启动应用程序 当应用程序启动时,它使用默认的 gce sa 凭据进行身份验证。 我所做的是创建一个 gke 服务帐户并使用 iam 策略绑定与 google 服务帐户绑定并添加工作负载身份用户角色 然后通过执行以下 2 个命令来注释 gke sa

问题仍然是我的 spring 引导使用默认的 gce sa 凭据 有人可以帮我解决这个问题吗?

我可以看到 serviceAccountName 已更改为新的 gke k8 SA,并且也在创建密码,mounted.But 部署的应用未使用此 Gke SA

注意:我正在使用 Helsm chart 进行部署

gcloud iam service-accounts add-iam-policy-binding \
  --member serviceAccount:{projectID}.svc.id.goog[default/{k8sServiceAccount}] \
  --role roles/iam.workloadIdentityUser \
  {googleServiceAccount}

kubectl annotate serviceaccount \
  --namespace default \
  {k8sServiceAccount} \
  iam.gke.io/gcp-service-account={googleServiceAccount}
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: helloworld
    appVersion: {{ .Values.appVersion }}
  name: helloworld
spec:
  replicas: 1
  selector:
    matchLabels:
      app: helloworld
  template:
    metadata:
      labels:
        app: helloworld
        environment: {{ .Values.environment }}
    spec:
      serviceAccountName: {{ .Values.serviceAccountName }}
      containers:
        - name: helloworld
          image: {{ .Values.imageSha }}
          imagePullPolicy: Always
          securityContext:
            allowPrivilegeEscalation: false
            runAsUser: 1000
          ports:
            - containerPort: 8080
          env:
          - name: SPRING_CONFIG_LOCATION
            value: "/app/deployments/config/"          
          volumeMounts:
            - name: application-config
              mountPath: "/app/deployments/config"
              readOnly: true
      volumes:
      - name: application-config
        configMap:
          name: {{ .Values.configMapName }}
          items:
          - key: application.properties
            path: application.properties

当你创建一个 pod 时,如果你没有指定一个服务帐户,它会自动分配到相同命名空间中的 default 服务帐户。如果您获得创建的 pod 的原始 json 或 yaml(例如,kubectl get pods/<podname> -o yaml),您可以看到 spec.serviceAccountName 字段已自动设置。

您可以使用自动安装的服务帐户凭据从 pod 内部访问 API,如访问集群 [1] 中所述。服务帐户的 API 权限取决于使用的授权插件和策略 [2]。

在 1.6+ 版本中,您可以通过在服务帐户上设置 automountServiceAccountToken: false 来选择不为服务帐户自动挂载 API 凭据:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: build-robot
automountServiceAccountToken: false
...

在 1.6+ 版本中,您还可以选择不为特定 pod 自动挂载 API 凭据:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  serviceAccountName: build-robot
  automountServiceAccountToken: false
  ...

如果两者都指定了 automountServiceAccountToken 值,则 Pod 规范优先于服务帐户。


[1] https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/

[2]https://kubernetes.io/docs/reference/access-authn-authz/authorization/#authorization-modules