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 from:
- The handler context. You can find the IAM token in the
access_tokenfield of thecontextparameter. - The metadata service in Google Compute Engine via the API.
To get an IAM token:
-
Create a function. When creating the first function version, select the runtime environment: Node.js or Python.
-
Disable the Add files with code examples option.
-
Click Continue.
-
Under Method, select ZIP archive.
-
Create a ZIP archive with the function code:
Node.jsPython-
Save the following code to a file named
index.jsto get the IAM token:-
From the handler context:
exports.main = async function (event, context) { return { 'statusCode': 200, 'headers': { 'Content-Type': 'text/plain' }, 'isBase64Encoded': false, 'body': context.token } }; -
Using the API:
const fetch = require("node-fetch"); let url = 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token'; let headers = {'Metadata-Flavor': 'Google'}; exports.main = async function (event) { const resp = await fetch(url, { headers: headers, }); return { code: resp.status, body: await resp.text() }; };
-
-
If you want to get your IAM token using the API, save the following code to a file named
package.json:{ "name": "my-app", "dependencies": { "node-fetch": "2.x" } } -
Add the
index.jsfile and, if using the API to get the IAM token, thepackage.jsonfile into theindex-js.ziparchive. -
Click Attach file and select the
index-js.ziparchive you have prepared.
-
Save the following code to a file named
index.pyto get the IAM token:-
From the handler context:
def main(event, context): return { 'statusCode': 200, 'headers': { 'Content-Type': 'text/plain' }, 'isBase64Encoded': False, 'body': context.token } -
Using the API:
import requests url = 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token' headers = {'Metadata-Flavor': 'Google'} def main(event, context): resp = requests.get(url, headers=headers) return { 'statusCode': 200, 'headers': { 'Content-Type': 'text/plain' }, 'isBase64Encoded': False, 'body': resp.content.decode('UTF-8') }
-
-
-
Create a function version.
-
In the Entry point field, specify
index.main. -
Under Parameters, select the service account to get an IAM token for or create a new one.
-
-
Run the function.
If the function runs successfully, you will get the following response:
{ "statusCode": 200, "headers": {"Content-Type": "text/plain"}, "isBase64Encoded": false, "body": { "access_token": "t1.9euelZrPm5O********", "expires_in": 43200, "token_type": "Bearer" } }