Akom's Tech Ruminations

Various tech outbursts - code and solutions to practical problems
Linux

Getting a systemd unit to read your .bashrc file for its environment

Posted by Admin • Thursday, June 11. 2015 • Category: Linux

Although it'd be nice to have all of your services not rely on their shell environment, sometimes it is unavoidable. In my case, some of the systems are still on init.d (redhat <=65, centos <=65, etc), but some are on systemd (7.0's, suse 12, etc). The old init scripts rely on the .bashrc file. In order to make the service run consistently on both flavors, I had to teach systemd to read the user's bashrc file. This is what it looks like.


[Service]
Type=simple
User=some_user
# Process the normal environment files for this user by starting a login shell
# and outputting it all in a temp file.  This makes it compatible
# with the non-systemd init scripts that still rely on .bashrc
ExecStartPre=/bin/bash --login -c 'env > /tmp/.magic-environment-file'
ExecStart=SERVICE_COMMAND
EnvironmentFile=-/tmp/.magic-environment-file
 
The "-" before the filename seems to make systemd ignore the error if the file is not there (for example, on the first run of the pre command). Now, obviously, you could just set your ~some-user/.bashrc as the EnvironmentFile - but your mileage will vary. systemd will not interpolate variables and it will ignore lines starting with "export"...

Note: there is a better way of handling this if you're using ruby/rvm, via wrappers.

0 Trackbacks

  1. No Trackbacks

2 Comments

Display comments as (Linear | Threaded)
  1. This has helped me, thanks very much!

  2. It worked for me. Thanks!

Add Comment


You can use [geshi lang=lang_name [,ln={y|n}]][/geshi] tags to embed source code snippets.
Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
Markdown format allowed


Submitted comments will be subject to moderation before being displayed.