首页 > 解决方案 > Google 计算引擎实例使用 api 启动/状态/停止

问题描述

如果我的过程结束,我需要启动谷歌云实例并停止。所以我尝试了来自https://cloud.google.com/compute/docs/reference/rest/v1/instances/get的 api 调用

为其创建了 API 密钥和 oAuth 客户端 ID,并尝试在邮递员应用程序中进行测试。

Authorization : Bearer <api_key>在标头和 URL 中使用 API 密钥作为key=<api_key>

但是这两种方法都给出了错误401 login required

然后我找到了 API Explorer

https://developers.google.com/apis-explorer/

我也有同样的错误。

我在做什么错误。我需要通过 PHP 代码实现实例启动和停止,因为它是后台进程。

PHP 卷曲响应

{
    "error": {
        "errors": [
            {
                "domain": "global",
                "reason": "authError",
                "message": "Invalid Credentials",
                "locationType": "header",
                "location": "Authorization"
            }
        ],
        "code": 401,
        "message": "Invalid Credentials"
    }
}

标签: phpgoogle-apigoogle-compute-enginegoogle-cloud-functionsgoogle-api-php-client

解决方案


我认为使用 env 变量实际执行此操作的最简单方法,因为 google api php 客户端库有一个简洁的方法。

require_once __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');

$client = new Google_Client();

$client->setApplicationName('RandomNameYouNeedToInsert/0.1');
$client->addScope(array('https://www.googleapis.com/auth/compute'));
$client->useApplicationDefaultCredentials();

$service = new Google_Service_Compute($client);

// TODO: Update placeholder values.
project = 'my-project';  
$zone = 'my-zone';  
$instance = 'my-instance';  

$response = $service->instances->start($project, $zone, $instance);
// TODO: Check if the response satisfies your request.

推荐阅读