Understanding environment variables

Hi,

Based on reading the docs and experimentation, environment variables are only applied to the root user in the container. Is that correct?

For example, if I have something like this in my profile:

config:
  environment.BAR: bar
  environment.FOO: foo

I can see these in the root user env with:

$ lxc exec c1 -- env

However, if I look at a different user env with:

$ lxc exec c1 -- sudo --user ubuntu env

FOO and BAR are not shown. If I use the -E arg in the sudo call above, they are shown.

Is that a correct understanding? Is there a way in a profile to apply the environment to other users or should that be done using a different mechanism during container creation?

Thanks.
Rob

1 Like

Interesting question, I would also like to know the answer.

As alternative you can probably use cloud-init.

That’s good idea. I put this cloud-init in the profile and removed the environment settings:

write_files:
- path: /etc/environment
  content: |
    FOO="FOO"
    BAR="BAR"
  append: true

Now it seems to work in the opposite way in that lxc exec c2 -- env doesn’t have the variables while lxc exec c2 -- sudo --user ubuntu env does.

I can make that work but I’m still fuzzy on the “best” way to do this with LXD.

Thanks for the reply.
Rob

sudo indeed strips environment variables by default, so this is expected.

There are several ways to get a shell into a container, https://blog.simos.info/using-command-aliases-in-lxd-to-exec-a-shell/

In a nutshell,

$ lxc ubuntu env
ubuntu@env:~$ env | grep Env
EnvFromConfigEnvironment=enabled
ubuntu@env:~$ logout
$ lxc shell env
root@env:~# env | grep Env
EnvFromCloudConfig=enabled
root@env:~# logout
$ lxc exec env -- sudo --user ubuntu --login
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

ubuntu@env:~$ env | grep Env
EnvFromCloudConfig=enabled
ubuntu@env:~$ logout

Therefore, have a look at my post and the lxc ubuntu alias. In effect, it does lxc exec without the need for sudo. It uses the new options in lxc exec to get a shell into the container.

1 Like

Thanks for the quick and helpful replies. I’ve got a better understanding now. :slightly_smiling_face: