如何从Terraform向Cloud Run函数传递Map变量?
解决Terraform传递Map变量到Cloud Run函数的方法
方法1:将Map序列化为JSON字符串作为环境变量传递
这是最直接的方案,利用Terraform的jsonencode函数把Map转成JSON格式的字符串,作为环境变量传给Cloud Run,之后在函数代码里解析这个JSON字符串还原成Map结构。
Terraform配置示例
variable "config_map" { type = map(string) default = { key1 = "value1" key2 = "value2" key3 = "value3" } } module "cloud_run_function" { source = "terraform-google-modules/cloud-foundation-fabric/google//modules/cloud-function-v2" # 其他必填配置(名称、区域、镜像等)省略 environment_variables = { APP_CONFIG = jsonencode(var.config_map) } # Pub/Sub触发器配置省略 }
函数代码示例(以Python为例)
import os import json def handler(event, context): # 从环境变量获取JSON字符串并解析为字典 config = json.loads(os.getenv("APP_CONFIG")) print(config["key1"]) # 输出 value1 # 执行后续业务逻辑
方法2:使用Secret Manager存储Map(适合敏感数据或大Map)
如果Map包含敏感信息,或者内容体积较大,推荐把序列化后的JSON字符串存在Secret Manager,再让Cloud Run挂载这个Secret,避免敏感数据直接暴露在环境变量中。
Terraform配置示例
variable "config_map" { type = map(string) default = { secret_key = "secret_value" api_url = "https://example.com/api" } } # 创建Secret Manager密钥 resource "google_secret_manager_secret" "function_config" { project = var.project_id secret_id = "function-config-secret" replication { automatic = true } } # 向密钥添加版本,存入序列化后的Map resource "google_secret_manager_secret_version" "function_config_version" { secret = google_secret_manager_secret.function_config.id secret_data = jsonencode(var.config_map) } module "cloud_run_function" { source = "terraform-google-modules/cloud-foundation-fabric/google//modules/cloud-function-v2" # 其他必填配置省略 # 配置Secret挂载为环境变量 secrets = [ { secret = google_secret_manager_secret.function_config.id version = google_secret_manager_secret_version.function_config_version.version env_var = "APP_CONFIG" } ] # 给Cloud Run服务账号添加访问Secret的权限 service_account_additional_roles = [ "roles/secretmanager.secretAccessor" ] # Pub/Sub触发器配置省略 }
函数代码示例
和方法1的代码逻辑一致,直接解析环境变量中的JSON字符串即可。
内容的提问来源于stack exchange,提问作者Junior Cloud Enginner
相关产品推荐
相关产品推荐

