Score:0

Setting global environment variables dynamically on startup

mw flag

I have an Ubuntu 18.04 vm which executes a script via /etc/profile.d. The script reaches out to an external data source (azure, in this case), pulls down some json, and converts it into environment variables. I was hoping these environment variables would be globally available to users, daemons, systemd, etc. but I'm realizing it's only for login shells. I'm reading that /etc/environment exists, but is static rather than a script file.

  1. Running this script in profile.d seems fragile..if the data source is transiently unavailable, that could impact the ability of my VM from booting.
  2. I had considered having a script append the values to /etc/environment, but that feels sketchy and I'm not certain that the env vars will be in scope when systemd runs.
  3. I was able to configure the particular systemd unit to behave like a login shell using the -l flag and that worked...but it is not the only unit or location where this will be required so that doesn't seem maintainable. Also, the external data calls are rate limited to something low...it really should only happen once.
  4. Similar to 3, I could directly reference the script to set environment variables everywhere I need it, but that has the same pitfalls and is not maintainable.

I'm now just spinning my wheels and am somewhat of a Linux newbie. What is the correct way to dynamically set global variables on startup?

Gunnar Hjalmarsson avatar
uz flag
Most display managers parse the files in `/etc/profile.d`, so for desktop users that ought to be a decent approach.
Switch386 avatar
mw flag
@GunnarHjalmarsson appreciate the response. How about for system processes/background jobs/daemons?
Gunnar Hjalmarsson avatar
uz flag
Well, processes which are started after the env. variables are set will see those env. variables. So, for instance, jobs started from a `.desktop` file in `/etc/xdg/autostart` will take such env. variables into account. But your way to ask is rather vague, and please note that I'm not an expert. Generally you can probably use systemd instead.
hr flag
... maybe turn your script into a [systemd.environment-generator](https://www.freedesktop.org/software/systemd/man/systemd.environment-generator.html) ?
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.