Using functions to get an IAM token for a service account
Written by
Updated at January 31, 2024
If the function version was created with a service account, you can get an IAM token for it from:
- The handler context. The IAM token is in the
access_token
field of thecontext
parameter. - The metadata service in Google Compute Engine via the API.
To get an IAM token:
-
Create a function.
-
Select the programming language and create a version of the function:
Node.jsPython- Prepare a ZIP archive with the function code:
- Save the following code to a file named
index.js
to 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() }; };
- From the handler context.
- If you 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
index.js
andpackage.json
(if you get your IAM token using the API) to a ZIP file calledindex-js.zip
.
- Save the following code to a file named
- Create a function version. Specify the following:
- Runtime environment:
nodejs16
- Code upload method:
ZIP archive
- File:
index-js.zip
- Entry point:
index.main
- Service account to get the IAM token for
- Runtime environment:
- Prepare a ZIP archive with the function code:
- Save the following code to a file named
index.py
to 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') }
- From the handler context.
- Add
index.py
to theindex-py.zip
archive.
- Save the following code to a file named
- Create a function version. Specify the following:
- Runtime environment:
python311
- Code upload method:
ZIP archive
- File:
index-py.zip
- Entry point:
index.main
- Service account to get the IAM token for
- Runtime environment:
- Prepare a ZIP archive with the function code:
-
Run the function.
The function response looks like this:
{ "access_token": "CggVAgAAABoBMRKABHGgpZ......", "expires_in": 42299, "token_type": "Bearer" }