php - 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"
}
}
解决方案
我认为使用 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.
推荐阅读
- c++ - 任何人都可以帮助在以下快速排序代码中找到错误,它显示分段错误(SIGSEGV)
- excel - 打开具有特定扩展名的文件
- linux - 有人在 Raspberry pi 3(ARM) 上正确安装了 aws-cli v2(x86_64; zipped) 吗?
- javascript - 如何以角度将字符串解析为特定模式?
- jenkins - 无法在舞台内跳过舞台
- r - R代码逐个打开文件执行操作并关闭打开的文件
- python - 如何使用python中的正则表达式删除列表中的重复行
- c++ - 在半透明窗口下查找像素的颜色
- typescript - 打字稿推断类型而不使用显式类型变量进行回调
- swift - swift - 如何确保最初定义特定属性的协议或类型?