【问题标题】:How to create a VM instance from an instance template within Cloud Functions?如何从 Cloud Functions 中的实例模板创建 VM 实例?
【发布时间】:2020-10-21 12:47:57
【问题描述】:

我需要根据我制作的模板启动一个 Google Compute 实例,该模板有一个启动脚本,可以从我的服务器下载最新的游戏服务器可执行文件并运行它。这一切都很好。

现在,我的自定义匹配器将确定所有当前游戏(游戏服务器的实例)是否已满,如果是,我希望它运行一个云函数,从我提到的模板创建另一个新实例以上(基本上为 12 名玩家充当大厅/游戏)。创建实例后,我需要云函数将新创建的实例的 IP 返回给任何调用它的对象(这将是我的游戏)。

我知道第一部分可以通过HTTP POST 进行,但我在云函数 docs/compute docs/admin SDK docs 中找不到任何地方,允许我创建实例并获取 IP,这可能吗?

编辑:我找到了这个documentation,但我还没有找到从模板启动 VM 的函数,该模板然后返回 VM 的对象 - 其中包括它的 IP...

【问题讨论】:

  • 首先,您能告诉我们更多有关您使用的模板的信息吗?
  • @MrTech 模板?它只是一个使用启动脚本运行 ubuntu 的自定义实例,该脚本下载我的游戏服务器可执行文件并运行它。它与这个问题无关,我在问是否可以通过云功能运行基于所述模板的实例?
  • 您今天如何创建虚拟机?你用控制台吗?命令行界面?
  • @guillaumeblaquiere 目前我必须从控制台中的模板手动启动实例,但无论哪种方式我都可以做到。我希望云功能来代替它与我的媒人相关联并使其全部动态化。
  • 你在I know the first part is possible via HTTP POST这里说什么。另外你能告诉我你的开发语言是什么吗?

标签: firebase google-cloud-platform google-cloud-functions google-compute-engine


【解决方案1】:

您可以直接使用 API。先创建VM,然后等待运行状态获取内外部IP

async function main() {
    const auth = new GoogleAuth({
        scopes: 'https://www.googleapis.com/auth/cloud-platform'
    });
    const client = await auth.getClient();

    const url = `https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/europe-west1-b/instances`
    const template= 'projects/PROJECT_ID/global/instanceTemplates/instance-template-1';

    const instanceName = 'example-instance'
    const body= '{ "name": "' + instanceName + '" }'

    let res = await client.request({ url: url + "?sourceInstanceTemplate=" + template,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: body
    });
    res = await client.request({ url: url + "/" + instanceName,
        method: 'GET'});

    while (res.data['status'] != 'RUNNING') {
        setTimeout(function(){},1000)
        res = await client.request({ url: url + "/" + instanceName,
            method: 'GET'});
    }
    //Internal Ip (interface0)
    console.log(res.data.networkInterfaces[0].networkIP);
    //External Ip
    console.log(res.data.networkInterfaces[0].accessConfigs[0].natIP);

}
main().catch(console.error);

我的 NodeJs 技能很低(样式、格式、习语,...),但这很管用。

【讨论】:

  • 谢谢,那将是我最后的选择。我假设我不能使用@google-cloud/compute npm 模块来做这样的事情,而不是直接发出请求?
  • InstanceTemplate 似乎不受 the library 支持
猜你喜欢
  • 2019-12-02
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
相关资源
最近更新 更多