Google 计算引擎实例 start/status/stop 使用 api

Google compute engine instance start/status/stop using api

我需要启动 google 云实例并在我的进程结束时停止。 所以我尝试了 api 来自 https://cloud.google.com/compute/docs/reference/rest/v1/instances/get

的电话

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

使用 API 键入 header Authorization : Bearer <api_key> 并在 URL 中键入 key=<api_key>

但是两种方法都报错 401 login required

然后我找到了API资源管理器

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"
    }
}

我认为使用 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.