15

I have created a linux service that runs as a deamon (and gets started from /etc/init.d/X). I need to set some environment variables that can be accessed by the application.

Here's the scenario. The application is a bunch of Perl AGI scripts that depend on (and therefore need to run as) asterisk user but asterisk doesn't have a shell. Ideally I'd just set this in /home/asterisk/.bashrc but that doesn't exist for asterisk.

How can I set environment variables for my app in the asterisk user's running environment so that my app can use them?

Fred Foo
  • 328,932
  • 68
  • 689
  • 800
domino
  • 1,899
  • 1
  • 20
  • 29

2 Answers2

28

Either set them in the startup script (/etc/init.d/yourdaemon), or put a line in that file that looks like:

. /etc/yourdaemon.env

and put the environment variables in that file, using the syntax export VAR=value. On Red Hat-like systems, I believe the correct place for such a file is /etc/sysconfig. Debian/Ubuntu seems to have /etc/default for this purpose.

Fred Foo
  • 328,932
  • 68
  • 689
  • 800
  • Tried that approach. The problem am having with that is that '/etc/init.d/yourdaemon' runs as root and so they are not available to my script, which runs as asterisk. – domino Oct 05 '10 at 15:26
  • 1
    start-stop-daemon --start --chuid=$USER --exec $DAEMON. This executes the app as $USER – domino Oct 05 '10 at 18:34
  • I checked the source code for the Debian version of `start-stop-daemon` and there's only one place where it touches the environment, to reset `HOME`. Can you post the `init.d` script? – Fred Foo Oct 05 '10 at 19:00
  • 6
    It worked. I am the one that had not used `export`. Thanks. Just a small point for future users - if there's a file to be sourced when running `/etc/init.d/myscript` it's good practice to add it to `/etc/default/myscript`. – domino Oct 06 '10 at 07:41
  • One thing I still don't understand though - how are the variables being exported to my deamons environment even though the init script is run by root? – domino Oct 06 '10 at 12:08
  • Every process passes its environment to its child processes. The `start-stop-daemon` program gets its environment from the `init.d` script; then it switches users *internally*, running as user `asterisk` for a short while and preserving its environment; then it starts your daemon. You'd have to use the `env` command explicitly to wipe the environment clean. – Fred Foo Oct 06 '10 at 12:20
  • @domino Your comment worked for me, not the answer. I don't know why. – AliBZ Jan 21 '14 at 23:12
3

If your distro of choice is now using systemd try systemctl edit --full asterisk.service and consider EnvironmentFile and Environment

These files normally live here: /etc/systemd/system/myservice.service e.g cron.service

KCD
  • 8,614
  • 3
  • 57
  • 66