Cloud Functions 允许您设置环境变量,以便在函数运行时访问配置数据。 这对于存储 API 密钥、数据库连接字符串等敏感信息非常有用,而且无需将它们硬编码到代码中。 🔐
你可以使用 gcloud functions deploy 命令来部署带有环境变量的函数。
gcloud functions deploy YOUR_FUNCTION_NAME \
--runtime YOUR_RUNTIME \
--trigger-http \
--set-env-vars KEY1=VALUE1,KEY2=VALUE2
替换 YOUR_FUNCTION_NAME, YOUR_RUNTIME, KEY1, VALUE1, KEY2, VALUE2 为你实际的值。
如果你使用 Terraform 管理你的基础设施,你可以使用 google_cloudfunctions_function 资源来配置环境变量。
resource "google_cloudfunctions_function" "default" {
name = "function-example"
description = "a new function"
runtime = "nodejs16"
available_memory_mb = 256
entry_point = "helloGET"
trigger_http = true
source_archive_bucket = "gcs-source-bucket"
source_archive_object = "archive.zip"
environment_variables = {
KEY1 = "VALUE1"
KEY2 = "VALUE2"
}
}
对于存储敏感信息(例如 API 密钥、数据库密码),强烈建议使用 Google Cloud Secret Manager。
Secret Manager 允许你安全地存储、管理和访问敏感信息。
在 Secret Manager 中创建一个新的 secret,并将你的敏感信息存储在其中。
授予你的 Cloud Function 的服务账号访问 secret 的权限。
在你的 Cloud Function 代码中,使用 Secret Manager API 来访问 secret 的值。
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
exports.helloWorld = async (req, res) => {
const client = new SecretManagerServiceClient();
const secretName = 'projects/YOUR_PROJECT_ID/secrets/YOUR_SECRET_NAME/versions/latest';
try {
const [version] = await client.accessSecretVersion({
name: secretName,
});
const payload = version.payload.data.toString();
console.log(`Secret value: ${payload}`);
res.status(200).send(`Secret value: ${payload}`);
} catch (error) {
console.error('Failed to access secret:', error);
res.status(500).send('Failed to access secret');
}
};
替换 YOUR_PROJECT_ID 和 YOUR_SECRET_NAME 为你实际的值。
永远不要将 API 密钥、密码等敏感信息硬编码到你的代码中。
使用环境变量或 Secret Manager 来存储和管理敏感信息。
只授予必要的服务账号访问敏感信息的权限。
定期轮换你的 API 密钥和密码,以降低安全风险。
通过遵循这些最佳实践,你可以安全地配置和使用 Cloud Functions 中的环境变量和敏感信息。 👍