yandex-cloud / nodejs-sdk

Yandex.Cloud NodeJS SDK
MIT License
64 stars 13 forks source link

Stop Comute Cloud from Yandex Functions #4

Closed ijakparov closed 4 years ago

ijakparov commented 4 years ago

Hello, how to stop certian Compute Cloud from Yandex functions using this sdk?

monsterzz commented 4 years ago

You can use InstanceService::stop and OperationService::get (to track operation completion).

Example code:

const yc = require('yandex-cloud');
const {InstanceService} = require('yandex-cloud/api/compute/v1');
const {OperationService} = require('yandex-cloud/api/operation');

const session = new yc.Session();
const instanceService = new InstanceService(session);
const operationService = new OperationService(session);

module.exports.handler = async function (event, context) {
    const instanceId = 'xxxxx';

    let op = await instanceService.stop({ instanceId });
    console.log(`op ${op.id} started`)

    while (!op.done) {
        op = await operationService.get({ operationId: op.id });
    }
    console.log(`op ${op.id} finished, spent ${op.timeSpent()}ms`);

    if (op.error) {
        throw new Exception(`op ${op.id} failed: ${JSON.stringify(op)}`);
    }

    return op;
}

Don't forget to assign service account for the functions and grant editor role to this service account in required folder.