Where (i.e. which file) to set/assign systemwide environment variable which e.g., nginx can read like NODE_ENV on FreeBSD? - environment

On FreeBSD, I need NODE_ENV=production and other systemwide environment variables to be set on startup, before nginx fires up.
Which is the right place i.e. file I do that?

Also, if you'd like to set some environment variables for an rc(8) service then you might also take a look at the ${name}_env and ${name}_env_file variables described in rc.subr(8). They allow you to set environment variables for services on FreeBSD in rc.conf(5), e.g.:
nginx_enable="YES"
nginx_env="NODE_ENV=production"

One option could be to add your environment variables to /etc/login.conf in the setenv capability, for example:
default:\
:passwd_format=sha512:\
:copyright=/etc/COPYRIGHT:\
:welcome=/etc/motd:\
:setenv=MAIL=/var/mail/$,BLOCKSIZE=K,NODE_ENV=production:\
...
From the login.conf man:
setenv list A comma-separated list of
environment variables and
values to which they are to
be set.
If you modity the /etc/login.conf file, don't forget to run:
cap_mkdb /etc/login.conf

Related

RHEL - Environment variable

I have an environment file named .env337_dev. I need to run this file to set the environment before running another command. How to run this file?
Inside the file, it contains several variables like this
export AB_HOME=/et/dev/abinitio/sit1/abinitio-V2 #/gcc3p32 # for 32-bit
export PATH=${AB_HOME}/bin:${PATH}
Apart from . ./.env337_devcommand which will run and set the environment, is there any other way to run this file ?
Are you looking for the user-specific .bashrc (bash is the default shell on RHEL 6) or a system-wide /etc/profile.d/<something>.sh? For the first, you would edit $HOME/.bashrc and append a line like . .env337_dev (it's still run before any "regular" command, because .bashrc is the Bash standard personal initialization file). Second option suggests that you use an absolute path.
If this doesn't answer your question, a more specific question and/or more details would be very helpful.
You tagged this ab-initio, so you should only be setting a very few environment variables, including:
export AB_HOME=<path-to-co>operating-system>
export PATH=$AB_HOME/bin:$PATH
If you are working with Ab Initio web applications:
export AB_APPLICATION_HUB=<path-to-application-hub>
export JAVA_HOME=<path-to-jdk>
export PATH=$JAVA_HOME/bin:$PATH
and specific settings for different applications, e.g.
export AB_MHUB_HOME=<path-to-metadata-hub-installation>
Typically you put those into the file .profile in your home directory, which shells evaluate for interactive sessions.

What is the best way to assign environment variable inside chef recipe?

I want to assign a system variable within chef recipe
I am using the following code:
env 'DEF_ADDR' do
value "http://#{node['ipaddress']}"
end
However, I am getting the below error on executing the recipe
ERROR: Cannot find a resource for env on redhat version 6.6
The env resource seems to be only for Windows environments:
Use the env resource to manage environment keys in Microsoft Windows.
If you want to define an environment variable only for the Chef Run, you can use Ruby:
ENV['DEF_ADDR'] = "http://#{node['ipaddress']}"
But this will only be accessible during the Chef Run.
If you want to define a system-wide environment variable, maybe the etc_environment cookbook could help you with that:
node.default['etc_environment']['DEF_ADDR'] = "http://#{node['ipaddress']}"
There is no consistent way to set global environment variables on Unix. Some distros support global-level shell includes via things like /etc/profile.d and the like, but this will have no effect on things run outside of a shell like direct SSH execution or running as a service.

PyCharm not updating with environment variables

When I use vim to update my environmental variables (in ~/.bashrc), PyCharm does not get the updates right away. I have to shut down the program, source ~/.bashrc again, and re-open PyCharm.
Is there any way to have PyCharm source the changes automatically (or without shutting down)?
When any process get created it inherit the environment variables from it's parent process (the O.S. itself in your case). if you change the environment variables at the parent level, the child process is not aware of it.
PyCharm allows you to change the environment variables from the Run\Debug Configuration window.
Run > Edit Configurations > Environment Variables ->
In my case pycharm does not take env variables from bashrc even after restarting
Pycharm maintains it's own version of environment variables and those aren't sourced from the shell.
It seems that if pycharm is executed from a virtualenv or the shell containing said variables, it will load with them, however it is not dynamic.
the answer below has a settings.py script for the virtualenv to update and maintain settings. Whether this completely solves your question or not i'm not sure.
Pycharm: set environment variable for run manage.py Task
I recently discovered a workaround in windows. Close Pycharm, copy the command to run Pycharm directly from the shortcut, and rerun it in a new terminal window: cmd, cmder, etc.
C:\
λ "C:\Program Files\JetBrains\PyCharm 2017.2.1\bin\pycharm64.exe"
I know this is very late, but I encountered this issue as well and found the accepted answer tedious as I had a lot of saved configurations already.
The solution that a co-worker told me is to add the environment variables to ~/.profile instead. I then had to restart my linux machine and pycharm picked up the new values. (for OSX, I only needed to source ~/.profile and restart pycharm completely)
One thing to be aware is that another coworker said that pycharm would look at ~/.bash_profile so if you have that file, then you need the environment variables added there
In case you are using the "sudo python" technique, be aware that it does not by default convey the environment variables.
To correctly pass on the environment variables defined in the PyCharm launch configuration, use the -E switch:
sudo -E /path/to/python/executable "$#"
This is simply how environment variables work. If you change them you have to re-source your .bashrc (or whatever file the environment variables are located in).
from dotenv import load_dotenv
load_dotenv(override=True)
Python-dotenv can interpolate variables using POSIX variable expansion.
With load_dotenv(override=True) or dotenv_values(), the value of a variable is the first of the values defined in the following list:
Value of that variable in the .env file.
Value of that variable in the environment.
Default value, if provided.
Empty string.
With load_dotenv(override=False), the value of a variable is the first of the values defined in the following list:
Value of that variable in the environment
Value of that variable in the .env file.
Default value, if provided.
Empty string.

Accessing Elastic Beanstalk environment properties in Docker

So I've been looking around for an example of how I can specify environment variables for my Docker container from the AWS EB web interface. Typically in EB you can add environment properties which are available at runtime. I was using these for my previous deployment before I switched to Docker, but it appears as though Docker has some different rules with regards to how the environment properties are handled, is that correct? According to this article [1], ONLY the AWS credentials and PARAM1-PARAM5 will be present in the environment variables, but no custom properties will be present. That's what it sounds like to me, especially considering the containers that do support custom environment properties say it explicitly, like Python shown here [2]. Does anyone have any experience with this software combination? All I need to specify is a single environment variable that tells me whether the application is in "staging" or "production" mode, then all my environment specific configurations are set up by the application itself.
[1] http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html#command-options-docker
[2] http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html#command-options-python
Custom environment variables are supported with the AWS Elastic Beanstalk Docker container. Looks like a miss in the documentation. You can define custom environment variables for your environment and expect that they will be passed along to the docker container.
I've needed to pass environment variable in moment docker run using Elastic Beanstalk, but, is not allowed put this information in Dockerrun.aws.json.
Below the steps to resolve this scenario:
Create a folder .ebextensions
Create a .config file in the folder
Fill the .config file:
option_settings:
-option_name: VARIABLE_NAME value: VARIABLE_VALUE
Zip the folder .ebextensions file along with the Dockerrun.aws.json plus Dockerfile and upload it to Beanstalk
To see the result, inside EC2 instance, execute the command "docker inspect CONTAINER_ID" and will see the environment variable.
At least for me the environment variables that I set in the EB console were not being populated into the Docker container. I found the following link helpful though: https://aws.amazon.com/premiumsupport/knowledge-center/elastic-beanstalk-env-variables-shell/
I used a slightly different approach where instead of exporting the vars to the shell, I used the ebextension to create a .env file which I then loaded from Python within my container.
The steps would be as follows:
Create a directory called '.ebextensions' in your app root dir
Create a file in this directory called 'load-env-vars.config'
Enter the following contents:
commands:
setvars:
command: /opt/elasticbeanstalk/bin/get-config environment | jq -r 'to_entries | .[] | "\(.key)=\"\(.value)\""' > /var/app/current/.env
packages:
yum:
jq: []
This will create a .env file in /var/app/current which is where your code should be within the EB instance
Use a package like python-dotenv to load the .env file or something similar if you aren't using Python. Note that this solution should be generic to any language/framework that you're using within your container.
I don't think the docs are a miss as Rohit Banga's answer suggests. Thought I agree that "you can define custom environment variables for your environment and expect that they will be passed along to the docker container".
The Docker container portion of the docs say, "No DOCKER-SPECIFIC configuration options are provided by Elastic Beanstalk" ... which doesn't necessarily mean that no environment variables are passed to the Docker container.
For example, for the Ruby container the Ruby-specific variables that are always passed are ... RAILS_SKIP_MIGRATIONS, RAILS_SKIP_ASSET_COMPILATION, BUNDLE_WITHOUT, RACK_ENV, RAILS_ENV. And so on. For the Ruby container, the assumption is you are running a Ruby app, hence setting some sensible defaults to make sure they are always available.
On the other hand, for the Docker container it seems it's open. You specify whatever variables you want ... they make no assumptions as to what you are running, Rails (Ruby), Django (Python) etc ... because it could be anything. They don't know before hand what you want to run and that makes it difficult to set sensible defaults.

Where to put environment variables when using nginx and Passenger on Ubuntu

I was trying to set up a system similar to heroku where I would store secret keys in environmental variables and then access them from my rails app like this:
secret = ENV['EMAIL_PASSWORD']
I know heroku lets you do heroku config:add EMAIL_PASSWORD=secret, and I wanted to do something like that for my own ubuntu box running nginx and Passenger.
Should I add these variables as exports in .bashrc or .bash_login so that on system reboot these variables are automatically set?
I'm not sure when each of those files gets read in.
You can use dotenv gem which loads the .env file as environmental variables. You can generate the .env file for different environments, and need not be rather should not checked into your repository.
Keep in mind that nginx may not be running under the same environment as you are, and usually (pronounced "Apache") we add env-vars in the server config file via SetEnv. However, nginx doesn't have such a feature... nor does it need one, I believe.
sudo -E /usr/local/sbin/nginx
When running nginx for it to be aware of your own user env vars.
Or, check out the env command (see here):
env EMAIL_PASSWORD=secret
To answer your question, yes, you should use export statements in your shell config files.
This is documented in nginx. It removes all environment variables except TZ when running the workers. If you want to add an environment variable, add the following to the top of the nginx configuration:
# The top of the configuration usually has things like:
user user-name;
pid pid-file-name;
# Add to this:
env VAR1=value1;
env VAR2=value2;
# OR simply add:
env VAR1;
# To inherit the VAR1 from whatever you set in bash
The normal export or anything you do in bash has no guarantee of getting passed on to nginx, due to the way the init scripts are written (we don't know if they're using sudo with a clean environment, etc). So I'd rather put these in the nginx configuration file itself, rather than depending on the shell to do it.
Edit: Fix link
(this is probably a overkill, but maybe it'll be useful)
Some things to keep in mind:
Environment variables are somewhat public, and can be seen by other processes as easily as added an option to the ps(1) command (like ps e $$ in bash) or looking at /proc/*/environ, though both are restricted at least to the same user (or root) on modern systems. Don't rely on them being secret if you have another fairly easy option available.
~/.bashrc is the wrong place for environment variables, since they can be computed once at login in ~/.bash_login, ~/.bash_profile, or ~/.profile, depending on your usage, and passed down to all descendent shells. In contrast, ~/.bashrc actions tend to be recomputed on every shell invocation (unless explicitly disabled).
Putting bash code in the ~/.profile can confuse other sh-descendent shells and non-shell tools which try to read that file, so having the bash-specific ~/.bash_login or -_profile contain the bash-specific things, and using . ~/.profile for the more general things (LESS, EDITOR, VISUAL, LC_COLLATE, LS_COLORS, etc), is friendlier to the other tools.
Environment variables in ~/.profile should be in the old Bourne shell form (VAR=value ; export VAR). On Linux, this isn't usually critical, though on other Unixen this can be a big issue when an older version of "sh" tries to read them.
Some X sessions will only read ~/.profile, not ~/.bash_login or the others mentioned above. Some will look for a ~/.xsession file will need to be modified to have . $HOME/.profile if it doesn't already somehow.
System-wide settings would be put instead in something like /etc/profile.d/similar-to-heroku.sh. Note that the ".sh" is only present since the file will be used with "." or "source" - shell scripts should never have command-name extensions in any form of Unix/Linux.
Most environment variables get ditched when one sudos to root, as ybakos points out. Similar issues show up in crontabs, at jobs, etc. When in doubt, adding env | sort > /tmp/envvars or the like a suspect script can really help in debugging.
Be aware some distributions have shell startup scripts so contorted they end up actually defying the order given in the bash(1) manual page. Anytime you find a default user ~/.profile checking for $BASH or $BASH_VERSION, you may be in one of these, um..., "interesting" environments, and may have to read through them to figure out where the control flow goes (they should be using a bash-specific ~/.bash_profile or ~/.bash_login, which includes the more generic ~/.profile by reference, thus letting the bash executable do the work instead of having to write $BASH checks in shell code).
~/.bash_profile (or ~/.bash_login) can certainly include . ~/.bashrc, but the environment variables belong in the ~/.bash_profile (if bash-specific) or the ~/.profile included from it (if you're using this mechanism and have envvars for everything else in there) as DeWitt says, just remember to put the . ~/.bashrc AFTER the .bash_profile's . ~/.profile and other environment variables, so that both login and all other invocations of the ~/.bashrc can rely on the envvars already being set. An Example ~/.bash_profile:
# .bash_profile
[ -r ~/.profile ] && . ~/.profile # envvars
[ -r ~/.bashrc ] && . ~/.bashrc # functions, per-tty settings, etc.
#---eof
The [ -r ... ] && ... works in any Bourne shell descendent and doesn't cause errors/aborts if the .profile is missing (I personally have a ~/.profile.d/*.sh setup as well, but this is left as an entirely optional exercise).
Note that bash only reads the first file of these three which it finds:
~/.bash_profile
~/.bash_login
~/.profile
...so once you have that one, the use of the other two is entirely under control of the user, from bash's perspective.
I put them in my nginx config, specifically in the server definition for the app using the passenger_env_var command:
server {
server_name www.foo.com;
root /webapps/foo/public;
passenger_enabled on;
passenger_env_var DATABASE_USERNAME foo_db;
passenger_env_var DATABASE_PASSWORD secret;
passenger_env_var SECRET_KEY_BASE the_secret_keybase;
}
This works for me. See the phusion passenger docs for more info.
I have a script in /usr/local/bin folder that sets some env vars and then executes Ruby. I define the path to Ruby in my (Apache, not Nginx) conf file to that file in /usr/local/bin.
example:
#!/bin/sh
# setup env vars here
export FOO=bar
export PATH_TO_FOO=/bar/bin
export PATH=$PATH:PATH_TO_FOO
# and execute Ruby with any arguments passed to this script
exec "/usr/bin/ruby" "$#"
You should read this response to another question, it will help:
https://stackoverflow.com/a/11765775/1217298
EDITED :
Ok sorry i read it too fast, you can check how to save your ENV variables here :
https://help.ubuntu.com/community/EnvironmentVariables
http://www.cyberciti.biz/faq/set-environment-variable-linux/
If you use Nginx as server on your local computer, you can define your env variable into your nginx config file.
location / {
...
fastcgi_param EMAIL_PASSWORD secret; #EMAIL_PASSWORD = secret
...
}
I'm using rbenv as a version manager. Good solution to store environment variables for the project was installing the rbenv-vars plugin and putting them in .rbenv-vars file.
Here is a useful post:
Deploying app ENV variables with Rbenv, Passenger and Capistrano
For those battling this that are using RVM. Make sure that your default environments file is including your user's .bashrc and .profile files
file: $rvm_path/environments/default
to find the path run this command:
ls -lah `whereis rvm`/environments/default
add these two lines before the first line in that file:
source $HOME/.bashrc
source $HOME/.profile
The best place to keep env variables for your project is /etc/profile.d/YOUR_FILE.sh,
Here you can find the documentation which explains in details where to keep env variables for different scenarios.
In case anyone had the same type of question as I did, here's a nice little writeup about the different .bash* files: http://www.joshstaiger.org/archives/2005/07/bash_profile_vs.html
In summary:
For the most part:
.bash_profile is read when you log into the computer and .bashrc is read when you start a new terminal. For Mac OSX .bash_profile is read with every terminal window you start.
So, the recommended procedure is to source .bashrc from .bash_profile so all the variables are set when you login to the computer. Just add this to .bash_profile:
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
You have to add the export lines into your .profile file under your home folder...
Environment variables are being set on login...

Resources