0

Up to now I added plain text environment variables in the first step of creating the Cloud Function, and in the second step I called for examples the db connection URL variables including the sensitive credentials with:

def my_cloud_function(request):
    from os import environ
    
    ...
    db_user = environ["DB_USER"]
    db_pass = environ["DB_PASS"]
    db_name = environ["DB_NAME"]
    db_host = environ["DB_HOST"]
    db_port = environ["DB_PORT"]
    ...

(or use os.getenv() instead of os.environ()).

But I do not want to expose these sensitive connection parameters in this variables menu, available to anyone with the rights who clicked on the "Variables" tab. It is awkward if I can click on the variables and see the login credentials of a colleague. But also the other parts of the db URL should just better be kept secret.

How can I use environment variables without exposing them to anyone, at best from an unreadable encrypted file that I can also push to git?

There are a couple of Q&A on Stack Overflow that go into this direction, but I could not find the answer:

I guess that this will need secrets, but how would that be done, where would they be stored? Or are there other ways like using the json that is passed as the request parameter?

questionto42
  • 7,175
  • 4
  • 57
  • 90

1 Answers1

4

The recommended way to manage secrets in Cloud Function is mounting the secrets from Secret Manager. This documentation explains very well how to set it up: https://cloud.google.com/functions/docs/configuring/secrets

In a nutshell:

  1. Create your secrets under Secret Manager;

enter image description here

  1. Edit your Cloud Function -> Advanced Options -> Security;
  2. Map the secrets you would like to be available during runtime;
  3. Grant the role roles/secretmanager.secretAccessor to the service account binded to the Cloud Function;
  4. Once done, you can use the secrets as environment variable (like you are used to and mentioned in your description);

enter image description here

questionto42
  • 7,175
  • 4
  • 57
  • 90
CaioT
  • 1,973
  • 1
  • 11
  • 20
  • 1
    You then need to choose in the drop-down menu "Reference method": "Exposed as environment variable" to make it a normal env var as before, no code change needed as in the comment above, but you need to delete the local plain text env vars that you had before if you read them here from secrets instead. And you need to use get the rights to do so (GRANT is not yet possible here so that the function does not deploy). – questionto42 Jan 18 '22 at 17:51