How to fix environment variables not working while running from system-d service in Go





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







9















I am using os.Getenv("APP_PATH") to read from the system environment variables and it works fine when running the build of the application normally. But I need to run this Go program as a service which I have done using systemd in which case it cannot read the environment variables. Is there any way of resolving this?










share|improve this question

























  • Why you cannot read variable in case of systemd?

    – Зелёный
    Jan 31 at 8:30






  • 1





    Add your service definition file to the question, otherwise we can only guess.

    – Peter
    Jan 31 at 8:37


















9















I am using os.Getenv("APP_PATH") to read from the system environment variables and it works fine when running the build of the application normally. But I need to run this Go program as a service which I have done using systemd in which case it cannot read the environment variables. Is there any way of resolving this?










share|improve this question

























  • Why you cannot read variable in case of systemd?

    – Зелёный
    Jan 31 at 8:30






  • 1





    Add your service definition file to the question, otherwise we can only guess.

    – Peter
    Jan 31 at 8:37














9












9








9








I am using os.Getenv("APP_PATH") to read from the system environment variables and it works fine when running the build of the application normally. But I need to run this Go program as a service which I have done using systemd in which case it cannot read the environment variables. Is there any way of resolving this?










share|improve this question
















I am using os.Getenv("APP_PATH") to read from the system environment variables and it works fine when running the build of the application normally. But I need to run this Go program as a service which I have done using systemd in which case it cannot read the environment variables. Is there any way of resolving this?







go






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 31 at 8:30









Flimzy

40.6k1367101




40.6k1367101










asked Jan 31 at 8:24









xava zylxava zyl

583




583













  • Why you cannot read variable in case of systemd?

    – Зелёный
    Jan 31 at 8:30






  • 1





    Add your service definition file to the question, otherwise we can only guess.

    – Peter
    Jan 31 at 8:37



















  • Why you cannot read variable in case of systemd?

    – Зелёный
    Jan 31 at 8:30






  • 1





    Add your service definition file to the question, otherwise we can only guess.

    – Peter
    Jan 31 at 8:37

















Why you cannot read variable in case of systemd?

– Зелёный
Jan 31 at 8:30





Why you cannot read variable in case of systemd?

– Зелёный
Jan 31 at 8:30




1




1





Add your service definition file to the question, otherwise we can only guess.

– Peter
Jan 31 at 8:37





Add your service definition file to the question, otherwise we can only guess.

– Peter
Jan 31 at 8:37












3 Answers
3






active

oldest

votes


















4














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.






share|improve this answer
























  • But now you are not reading environment variables anymore?

    – monocell
    Jan 31 at 13:55



















6














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(see User and Group section).






share|improve this answer































    2














    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






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54456186%2fhow-to-fix-environment-variables-not-working-while-running-from-system-d-service%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      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.






      share|improve this answer
























      • But now you are not reading environment variables anymore?

        – monocell
        Jan 31 at 13:55
















      4














      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.






      share|improve this answer
























      • But now you are not reading environment variables anymore?

        – monocell
        Jan 31 at 13:55














      4












      4








      4







      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.






      share|improve this answer













      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.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 31 at 8:38









      ShakShak

      793




      793













      • But now you are not reading environment variables anymore?

        – monocell
        Jan 31 at 13:55



















      • But now you are not reading environment variables anymore?

        – monocell
        Jan 31 at 13:55

















      But now you are not reading environment variables anymore?

      – monocell
      Jan 31 at 13:55





      But now you are not reading environment variables anymore?

      – monocell
      Jan 31 at 13:55













      6














      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(see User and Group section).






      share|improve this answer




























        6














        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(see User and Group section).






        share|improve this answer


























          6












          6








          6







          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(see User and Group section).






          share|improve this answer













          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(see User and Group section).







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 31 at 8:48









          ЗелёныйЗелёный

          30.3k75371




          30.3k75371























              2














              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






              share|improve this answer




























                2














                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






                share|improve this answer


























                  2












                  2








                  2







                  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






                  share|improve this answer













                  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







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 31 at 8:31









                  Keith John HutchisonKeith John Hutchison

                  2,66442733




                  2,66442733






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54456186%2fhow-to-fix-environment-variables-not-working-while-running-from-system-d-service%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                      SQL update select statement

                      'app-layout' is not a known element: how to share Component with different Modules