Skip to content

Use environment variables

View as Markdown

Environment variables hold configuration, such as database URLs, service endpoints, and application settings, separately from your function’s code. You add them when you create the function or later, and your code reads them at runtime. To change a value, change the variable and save.

You need a function that is Running or Failed. Its variables are read-only while it is Creating or Deploying. To add variables while you create a function, see Create a function.

A key uses letters, digits, and underscores, and must start with a letter or underscore. It can be up to 50 characters long. Each key must be unique within a function. Functions reserves the name PORT for its own use. Choose another name. To set the port a custom container listens on, see Deploy a custom container image.

  1. In Compute > Functions, click the function’s name to open its page.
  2. Under Function Configuration, find Environment variables. If the function has no variables yet, click Add Variables.
  3. Enter a Key and a Value.
  4. Click Save to apply the change.

In a Python HTTP runtime, read a variable with os.environ:

import os
database_url = os.environ.get("DATABASE_URL")

In a Node.js HTTP runtime, read it with process.env:

export const handler = async (event) => {
const serviceUrl = process.env.SERVICE_URL;
return { statusCode: 200, body: "ok" };
};

In each example, replace the variable name in os.environ.get or process.env with the key you set.

After you save, the function redeploys. Select the function in the Functions list and open the Info tab below the list. Check that Version went up by one. Then call the function to confirm it reads the new value. See Call a function.

If the function fails to start after you add a variable, check its logs. See View logs and monitoring and Troubleshooting Functions.