How to change the value of an Environment variable from the code of Google Cloud Function?

Viewed 785

I'm trying to understand how to use environment variables properly for Google Cloud Functions.

I've deployed a function and I want to write and read it's environment variable (e.g.: XXX).

if not os.environ.get("XXX"):
    print("XXX_SET_DEFAULT")
    os.environ.setdefault("XXX","1")
else:
    print("XXX_SET")
    os.environ["XXX"] = "1"
print("XXX_GET", os.environ["XXX"])

After triggering the function, the value initially set in the Runtime environment variables list does not change.

Although the behavior is little bit different, because when I deploy the variable with the function with a dummy value I can see XXX_SET string in the logs, but when I don't deploy the variable first, for the first run I can see XXX_SET_DEFAULT, then for the second run there is XXX_SET.

I've set the variables with (and from the UI too):

gcloud functions deploy my_func \
    ...
    --set-env-vars XXX=xxx

Questions:

  • Is it possible to set this variable from the python code somehow?
  • What makes this difference in the logs (XXX_SET_DEFAULT, XXX_SET vs. XXX_SET, XXX_SET )
  • Why the value of this variable doesn't get set from python code?
    • is it somehow related to the multiple instantiations of the function (when needed)?
  • What is the difference between Runtime environment variables and Build environment variables?
    • can I deploy the variables between the Build environment variables somehow?
  • What are the best practices for using the Environment Variables with cloud functions at Google?
1 Answers

You are not meant to change environment variables in GCFs. They are there to set configurations.

Here are some basics:

  • Functions are run in (docker) containers. These ensure that they always run in a clear and consistent environment.
  • Build environment variables are for when the container is built. Unless you are messing with how you build, you will not need these.
  • Runtime environment variables are for when the function runs in the container. These are the ones you can access with your code.

What this means, is every time you run a function, it'll get a new container, with all the variables set to whatever you've set them in configuration.

Now, it is possible that GCF in the background reuses some of the containers, and you may see some persistance but you cannot rely on this.

In conclusion:

  • Environment variables are there to provide a simple configuration option for your code, that can be changed without having to change your code.
  • In general, it's better to treat them as read-only, even though you can change them, those changes will be discarded when the container where your code runs is discarded.
  • If you want to persist data between functions, use a database.
Related