How to read environment variables in R-Shiny apps

R-Shiny apps can’t access system-wide environment variables by design. How to work with them anyway? I got some suggestions to my question on Mastodon from the community. In the end, together with my colleague Sebi, I implemented this solution:

1.Assume a machine with two environment variables called MY_ENV_VAR and MY_ENV_VAR2

2.Commit a env (not .env!) that references the systemwide variables:

MY_ENV_VAR=“${MY_ENV_VAR}“
MY_ENV_VAR2=“${MY_ENV_VAR2}“

3. Copy the env file to specific shiny app’s folder as .env: cp env srv/shiny-server/my-app/.env

4. Allow the shiny user to read the .env file: chown shiny srv/shiny-server/my-app/.env

5. Read .env file in the Shiny app with base::readRenviron(".env")

2 Kommentare

Charles 15. September 2024 Antworten

R Shiny apps can actually access system-wide environment variables. Where did you read it was not the case „by design“? I’m curious.

Run `Sys.getenv()` and you will see the list of preloaded environment variables.

Even if a variable is not available, you can use `system(„echo $VARIABLE“, intern = TRUE)` to get any system variable.

Also the common way to define environment variables in R (and Shiny) is to create a file named `.Renviron` at the root of the project directory (or in the home directory of the user) and define the variables there.

A best practice is also to „chmod 600“ the environment file since they tend to contain secrets.

Katharina 17. September 2024 Antworten

Hey Charles,
thanks for your comment!

That Shiny apps cannot access system-wide environment variables by design I infered this from these posts:
https://forum.posit.co/t/how-to-access-os-environment-variable-from-shiny-apps-server-r/23822/2
https://groups.google.com/g/shiny-discuss/c/nNs0kztwdWo/m/90InjZXfAPEJ (Joe Cheng)

`Sys.getenv()` does not (always) work, there are plenty of stackoverflow posts out there, e.g. https://stackoverflow.com/questions/36853408/sys-getenv-returns-empty-in-shiny-apps
Plus my own experience. I am more than happy if this is not the case.

I know, that `.Renviron` are used in a common way. My usecase is a Kubernetes cluster with databases that I want to access with a Shiny app and the credentials are stored in systemwide environment variables. Copy pasting them first to an `.Renviron` does not make sense to me or is basically the same workflow I proposed.

Thanks for the `chmod 600`!

Schreibe einen Kommentar zu Katharina Antworten abbrechen