使用统一的代码库在多个区域部署函数

Deploying in functions in multiple regions with a unified codebase

我有一个相当简单的要求,因为我需要多个区域中的 Firebase 函数、存储桶和 firestore 数据库的相同副本,以满足数据不会在区域之间移动。一个用于欧盟、英国、美国等。

因为每个 firebase 项目只能有一个 firestore 数据库,所以我正在按照建议为每个区域创建一个新项目。我可以使用 firebase 项目环境变量将我的存储桶 read/writes 重定向到正确的区域,以定义要写入的存储桶。到目前为止一切顺利。

现在最后一个瓶颈是函数本身。

问题是默认函数转到“us-central1”而不是 firebase 项目区域,因此似乎指定区域的唯一方法是在代码库等中使用 .region(“eu-west3”) 说明符.但是因为我想要一个跨所有项目的统一代码库,所以在每个项目的基础上更改它有点麻烦。

关于如何最好地管理它有什么建议吗?

您可以使用 firebase functions:config:set:

将区域值存储为环境配置
firebase functions:config:set env.region="us-central1" 

After running functions:config:set, you must redeploy functions to make the new configuration available.

然后 get the environment variable 在您的函数中使用此代码:

exports.myFunction = functions
    .region(functions.config.env.region)
    .https.onRequest((req, res) => {
            res.send("Hello");
    });

有了这个,您不再需要在代码中更改区域。但是如果你想改变区域,你仍然必须在每个项目上更改配置和重新部署功能。


另一个解决方案是使用 Cloud Build 来自动化一切。我还没有完全测试它,但这是我能想到的。

首先,follow the instructions 关于如何使用 Firebase 构建工具。 Cloud Build 上的 运行 Firebase CLI 命令需要此社区提供的图像。完成后,确保在项目中启用了以下 API:

  1. 云资源管理器API
  2. Firebase 管理API

并且在您的 Cloud Build 设置中,Firebase Admin 已启用。

然后试试这个 cloudbuild.yaml 文件。 Cloud Build 将从您的项目和其他项目中使用该工具:

steps:
# Setup First Project
  - name: gcr.io/project-id1/firebase
    id: 'Use Project 1'
    args: ['use', 'project-id1'] 

  - name: gcr.io/project-id1/firebase
    id: 'Set Firebase Environment Config'
    args: ['functions:config:set', 'env.region=us-central1'] 
     
  - name: gcr.io/project-id1/firebase
    id: 'Deploy function1'
    args: ['deploy', '--project=project-id1', '--only=functions']

# Setup Second Project
  - name: gcr.io/project-id1/firebase
    id: 'Use Project 2'
    args: ['use', 'project-id2'] 

  - name: gcr.io/project-id1/firebase
    id: 'Set Firebase Environment Config'
    args: ['functions:config:set', 'env.region=eu-west3'] 
     
  - name: gcr.io/project-id1/firebase
    id: 'Deploy function2'
    args: ['deploy', '--project=project-id2', '--only=functions']

# And so on...

Note: Change project-id with your actual Project ID.

exports.myFunction = functions
.region(functions.config.env.region)
.https.onRequest((req, res) => {
        res.send("Hello");
});

config 是一个函数,所以这个调整是必要的:

exports.myFunction = functions
.region(functions.config().env.region)
.https.onRequest((req, res) => {
        res.send("Hello");
});