2021 年更新:现在有一个 Cloud Run 预览版,用于将机密加载到环境变量或卷中。 https://cloud.google.com/run/docs/configuring/secrets
这个问题现在得到了回答,但是我在使用 Cloud Run with Java & Quarkus 以及使用 GraalVM 创建的本机映像时遇到了类似的问题。
虽然 Cloud Run 在撰写本文时是一项非常有趣的技术,但它缺乏通过 Cloud Run 配置加载机密的能力。在进行本地开发时,这无疑增加了我的应用程序的复杂性。
此外,谷歌的文档真的很差。快速入门缺少一个明确的 Java 示例来获取秘密 [1],而无需使用相同的方法进行设置 - 我希望这是最常见的用例!
javadoc 本身似乎在很大程度上是使用 protobuf 语言自动生成的。有各种类似命名的方法,如getSecret
,getSecretVersion
和accessSecretVersion
我真的很想看到谷歌在这方面做出一些改进。我认为专门的团队为具有适当文档的通用语言制作库并没有太多要求。
这是我用来加载此信息的片段。它需要 GCP Secret 库和 GCP Cloud Core 库来加载项目 ID。
public String getSecret(final String secretName) {
LOGGER.info("Going to load secret {}", secretName);
// SecretManagerServiceClient should be closed after request
try (SecretManagerServiceClient client = buildClient()) {
// Latest is an alias to the latest version of a secret
final SecretVersionName name = SecretVersionName.of(getProjectId(), secretName, "latest");
return client.accessSecretVersion(name).getPayload().getData().toStringUtf8();
}
}
private String getProjectId() {
if (projectId == null) {
projectId = ServiceOptions.getDefaultProjectId();
}
return projectId;
}
private SecretManagerServiceClient buildClient() {
try {
return SecretManagerServiceClient.create();
} catch(final IOException e) {
throw new RuntimeException(e);
}
}
[1] - https://cloud.google.com/secret-manager/docs/reference/libraries