How to fix environment variables not working while running from system-d service in Go
You can follow along from here to make the use of the environment variables. The way I am using to implement environment variables in my project is GODOTENV go library. It is very easy to implement and platform independent.
Simply run
err = godotenv.Load(filepath.Join(path_dir, ".env"))
and you are done. Now you can use you code os.Getenv("APP_PATH")
to read the keys from your .env
file and it works perfectly fine with systemd service.
It depends on how you're running your systemd service. Systemd provide a bunch of derictive you should use:
[Unit]
Description=My service
After=network.target
[Service]
Type=simple
User=user
Group=user
EnvironmentFile=/home/user/env_file
ExecStart=/bin/bash -c -l '/home/user/go_program'
# ... other directive goes here
[Install]
WantedBy=multi-user.target
EnvironmentFile
- the file with ENV variables, that file will be loaded for you by systemd.User
,Group
- under which user and group the program should run.ExecStart=/bin/bash -c -l '/home/user/go_program'
- the-l
options makes bash act as if it had been invoked as a login shell, so the variable in your.bash_profile
will be loaded(seeUser
andGroup
section).
We have our environment variables in a .env file and use godotenv
import {
"github.com/joho/godotenv"
}
func main() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
environmentPath := filepath.Join(dir, ".env")
err = godotenv.Load(environmentPath)
fatal(err)
}
and it works when we run our apps in daemon mode