Using functions to get an IAM token for a service account

If the function version was created with a service account, you can get an IAM token for it:

Get an IAM token from the context

If you create a function in a runtime environment supported by Cloud Functions, you can get an IAM token from the handler context (which is the second parameter: context).

To get an IAM token, add the row token: context.token to the function code and call the function:

  1. Save the following code to a file named index.js:

    exports.handler = async function (event, context) {
        return {
            token: context.token,
            event: event
  2. Create a function version using the index.js file.

  3. Run the function.

    The function response looks like this:

      "token": {
        "access_token": "CggVAgAAABoBMRKABHGgpZ......",
        "expires_in": 42299,
        "token_type": "Bearer"
      "event": {
        "payload": ""

    The IAM token will be returned in the access_token field of the response. The remaining lifetime of the IAM token is specified in the expires_in field.

Get an IAM token using the API

If you work with Yandex.Cloud from inside the VM, you can get an IAM token from the VM's metadata in Google Compute Engine format, and also add this logic to your function. Read more about this in Working with Yandex.Cloud from inside a VM.