Friday, April 15, 2016

Add environment variables permanently on MAC OS

I have recently decided to externalize some configuration settings of a side project I'm working on. This is a pretty straightforward task on Linux, but it was quite different on Mac as defining this environment variables in .bash_profile won't make them available to all applications. To achieve that, I had to do the following:

  1. I added my environment variables to .bash_profile as usual
    • export OPENSHIFT_MYSQL_DB_HOST=localhost
    • export OPENSHIFT_MYSQL_DB_PORT=3306
    • export OPENSHIFT_APP_NAME=dev
    • export OPENSHIFT_MYSQL_DB_USERNAME=appuser
    • export OPENSHIFT_MYSQL_DB_PASSWORD=apppwd
  2. Create a file openshift-env.plist in ~/Library/LaunchAgents that contains: 
    •  <?xml version="1.0" encoding="UTF-8"?>
      <plist version="1.0">
      <dict>
       <key>Label</key>
       <string>openshift-env</string>
       <key>ProgramArguments</key>
       <array>
       <string>bash</string>
       <string>-l</string>
       <string>-c</string>
       <string>
       $HOME/.openshift-env.sh
       </string>
       </array>
       <key>RunAtLoad</key>
       <true/>
      </dict>
      </plist>
  3. Create a shell script openshift-env.sh using this command: nano ~/.openshift-env.sh and paste this:
  4. grep export $HOME/.bash_profile | while IFS=' =' read ignoreexport envvar ignorevalue; do launchctl setenv ${envvar} ${!envvar} done
  5. Make sure the script is executable: chmod +x ~/.openshift-env.sh
  6. Now, reload the launch agent for the current session: launchctl load ~/Library/LaunchAgents/openshift-env.plist
  7. If you add or remove an environment variable and you want to reload your configuration, you should run the following command:
    • launchctl unload ~/Library/LaunchAgents/osx-env-sync.plist 
    • launchctl load ~/Library/LaunchAgents/osx-env-sync.plist
I hope this helps!

No comments:

Post a Comment