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.
Before you begin
Section titled “Before you begin”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.
Key names
Section titled “Key names”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.
Add environment variables
Section titled “Add environment variables”- In Compute > Functions, click the function’s name to open its page.
- Under Function Configuration, find Environment variables. If the function has no variables yet, click Add Variables.
- Enter a Key and a Value.
- Click Save to apply the change.
Read them from code
Section titled “Read them from code”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.
Check that the change applied
Section titled “Check that the change applied”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.