我正在尝试从云函数启动计算引擎 VM,但是当我从 GCP 控制台测试该函数时出现以下错误:
ApiError: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential
当我尝试使用触发器 URL 运行它时,我收到 403 错误。
我尝试将 Compute Admin 角色添加到 IAM & Admin 选项卡中的服务帐户,但这没有帮助。
功能如下:
/**
* Start the Minecraft server
*/
const Compute = require('@google-cloud/compute');
const compute = new Compute();
const zone = compute.zone('europe-north1-a');
const vm = zone.vm('mc-server');
async function get_server_ip() {
return new Promise(function(resolve, reject) {
vm.getMetadata().then((data) => {
resolve(data[0].networkInterfaces[0].accessConfigs[0].natIP);
});
});
}
async function check_if_server_is_ready() {
const server_ip = await get_server_ip();
const ready = !!server_ip;
return ready
}
async function sleep(milliseconds) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, milliseconds);
});
}
exports.startInstance = async function startInstance(req, res) {
// Start the VM
console.log('about to start a VM');
vm.start(function(err, operation, apiResponse) {
console.log('instance start successfully');
});
console.log('the server is starting');
while(!(await check_if_server_is_ready())) {
console.log('Server is not ready, waiting 1 second...');
await sleep(1000);
console.log('Checking server readiness again...');
}
console.log('the server is ready');
res.status(200).send('Minecraft Server Started! You are now spending REAL MONEY! <br />' );
};
我也有关闭虚拟机的功能,但也有同样的问题。