Server/Linux
systemd에서 유저의 환경변수를 읽지 않는경우, 유저의 환경변수를 읽게 설정하는 법
iliosncelini
2019. 8. 13. 14:46
https://bacchi.me/linux/systemd-tips/
systemdでユーザーの環境変数を読み込むようにする
systemdでユーザーの環境変数が読み込まれず
うまくサービスが立ち上がらないという問題がありました。
調べてみると、systemdは.barshrcや.bash_profileに
定義した環境変数を読んでくれないということがわかりました。
環境変数を読み込ませたい場合は一手間かけてあげれば大丈夫なので、その方法をまとめてみました。
/etc/sysconfig/USER_NAME に読み込ませたい環境変数を書く
以下の要領でserviceを動かすユーザーが読み込む環境変数を定義するファイルを設定します。
| # cat <_EOF_ > /etc/sysconfig/test LANG=ja_JP.UTF-8 PATH=/home/test/.plenv/shims:/home/test/.plenv/bin:/home/test/.rvm/gems/ruby-1.8.7-p374/bin:/home/test/.rvm/gems/ruby-1.8.7-p374@global/bin:/home/test/.rvm/rubies/ruby-1.8.7-p374/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/test/.rvm/bin:/home/test/.local/bin:/home/test/bin:/usr/local/bin HOGE=HOGE PIYO=PIYO _EOF_ |
systemd設定ファイルの[service]ディレクティブにEnvironmentFileを定義する
上記で作成した環境変数を定義したファイルを読み込ませるために、
systemd設定ファイルの[service]ディレクティブにEnvironmentFileの行を追加してやります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # cat /etc/systemd/system/plapp.service [Unit] Description=plapp Start-Stop Switch # unit is started after the listed unit finished starting up After=syslog.target network.target [Service] Type=forking User=test Group=test ExecStart=/usr/local/bin/plapp start ExecStop=/usr/local/bin/plapp stop [Install] # run level3 WantedBy=multi-user.target |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # cat /etc/systemd/system/plapp.service [Unit] Description=plapp Start-Stop Switch # unit is started after the listed unit finished starting up After=syslog.target network.target [Service] Type=forking User=test Group=test EnvironmentFile=/etc/sysconfig/test ExecStart=/usr/local/bin/plapp start ExecStop=/usr/local/bin/plapp stop [Install] # run level3 WantedBy=multi-user.target |
サービスの再起動
ここまでの設定が終わればサービスの再起動を行います。
場合によっては設定ファイルのリロードを求められる場合があるのでケースバイケースで。