使用 Spring Boot 的 GKE 工作负载身份

问题描述 投票:0回答:1

我正在尝试将 GKE 中运行的 Spring Boot 应用程序连接到 GC 中的 cloudSQL 数据库。谷歌建议的方法是通过工作负载身份。

除了将云管理员角色添加到服务帐户之外,我还遵循了这些说明,我什至运行了测试 Pod 以确保我的 Pod 使用正确的服务帐户运行。然后我像这样运行我的部署。

apiVersion: "apps/v1"
kind: "Deployment"
metadata:
  name: "hello-world"
  namespace: my-dev
  labels:
    app: "hello-world"
spec:
  replicas: 1
  selector:
    matchLabels:
      app: "hello-world"
  template:
    metadata:
      labels:
        app: "hello-world"
    spec:
      containers:
        - name: "hello-container"
          image: "my-region-docker.pkg.dev/my-project/my-repo/my-tag"
          ports:
            - containerPort: 8080
      serviceAccountName: new-service-account
      nodeSelector:
        iam.gke.io/gke-metadata-server-enabled: "true"

我的理解是,一旦我们这样做了,我们就不需要用户名/密码来连接到数据库,因为服务帐户已获得连接授权。

但是,我无法在 Spring Boot 方面实现这一点。我已经尝试了此page

的多种组合
spring.datasource.url=jdbc:postgresql:///DATABASE_NAME?cloudSqlInstance=INSTANCE_CONNECTION_NAME&socketFactory=com.google.cloud.sql.postgres.SocketFactory

spring.cloud.gcp.sql.*

属性,但我还没有设法使其连接。

我不需要用户名/密码的假设是错误的还是我的配置错误?

使用的属性

[email protected]
spring.datasource.password=mockpassword # this is the actual value that I placed since you told me not to leave empty
spring.datasource.url=jdbc:postgresql:///mydb?cloudSqlInstance=project-id:region:mydb&socketFactory=com.google.cloud.sql.postgres.SocketFactory&enableIamAuth=true
spring-boot google-kubernetes-engine google-cloud-sql gke-networking workload-identity
1个回答
1
投票

您的数据库配置似乎需要 Cloud SQL JDBC Connector 才能使用 IAM 身份验证和工作负载身份。

首先,将

&enableIamAuth=true
添加到您的 JDBC URL。它应该看起来像这样:

spring.datasource.url=jdbc:postgresql:///DATABASE_NAME?cloudSqlInstance=INSTANCE_CONNECTION_NAME&socketFactory=com.google.cloud.sql.postgres.SocketFactory&enableIamAuth=true

此外,您还需要设置用户和密码的数据库属性。

username
需要是 Google 服务帐户电子邮件的缩写版本。
password
不能为空,否则 Postgres JDBC 驱动程序将抛出异常,但由于您设置了
enableIamAuth=true
,因此将不会使用密码值。

spring.datasource.username=<SHORTENED_SERVICE_ACCOUNT_NAME>
spring.datasource.password=password

替换为 Postgres 数据库使用的缩短的服务帐户名称。

您必须将完整的 IAM 用户电子邮件缩短为数据库用户名。由于 对数据库用户名中允许的字符的不同限制,Mysql 和 Postgres 的不同之处在于它们如何将 IAM 电子邮件地址缩短到数据库中 用户名。

  • Mysql:截断 IAM 电子邮件,删除
    @
    以及后面的所有内容。
  • Postgres:如果 IAM 电子邮件以
    .gserviceaccount.com
    结尾,请删除 电子邮件中的
    .gserviceaccount.com
    后缀。

例如,如果完整的 IAM 用户账户是

[email protected]
,然后是缩短的数据库用户名 对于 Mysql 来说是
my-sa
,对于 Postgres 来说是
[email protected]

© www.soinside.com 2019 - 2024. All rights reserved.