How to use environment variable to avoid hard coding postgresql username and password in database.yml?

I created a new Rails application called sample_app and I use postgresql as my db (I already created the postgresql username and password). I use this setup guide https://gorails.com/setup/ubuntu/16.04

So, I run this command rails new sample_app -d postgresql. And then I need to edit config/database.ymlto combine the username and password with my username and postgresql password that I just created. But I do not want to hard code, because I will use git.

I found this tutorial from the digital ocean that suggests using:

username: <%= ENV['APPNAME_DATABASE_USER'] %>
password: <%= ENV['APPNAME_DATABASE_PASSWORD'] %>

Is this the correct code? If so, since my application is called sample_app, should my code be?

username: <%= ENV['SAMPLE_APP_DATABASE_USER'] %>
password: <%= ENV['SAMPLE_APP_DATABASE_PASSWORD'] %>

If this is wrong, can you help me? Thank!

+4
source share
3 answers

There are many ways to set environment variables.

Here are two of them,

Option one: set ENV variables via yml file

Create a file config/local_env.yml:

config / local _env.yml:

SAMPLE_APP_DATABASE_USER: 'your username'
SAMPLE_APP_DATABASE_PASSWORD: '******'

Above are the names that you will use, for example . these may be names as you wish . you can take any name, but we must use the same name in the ENV link . ENV['SAMPLE_APP_DATABASE_USER']

add it to gitignore:

/config/local_env.yml

Change the code in application.rb

application.rb:

config.before_configuration do
  env_file = File.join(Rails.root, 'config', 'local_env.yml')
  YAML.load(File.open(env_file)).each do |key, value|
    ENV[key.to_s] = value
  end if File.exists?(env_file)
end

config/local_env.yml, / .

:

username: <%= ENV['SAMPLE_APP_DATABASE_USER'] %>
password: <%= ENV['SAMPLE_APP_DATABASE_PASSWORD'] %>

: Figaro Gem

Rubys , . config/application.yml , - Rails.

. Gemfile :

gem 'figaro'

bundle install

:

$ bundle exec figaro install

config/application.yml .gitignore file, git.

/ config/application.yml:

SAMPLE_APP_DATABASE_USER: 'your username'
SAMPLE_APP_DATABASE_PASSWORD: '******'

ENV:

ENV["SAMPLE_APP_DATABASE_USER"]

.

+6

, ...

username: <%= ENV['CARROTS'] %>
password: <%= ENV['BEANS'] %>

, script CARROTS BEANS.

+3

dotenv-rails

Gemfile:

gem 'dotenv-rails', :groups => [:development, :test]

. .env :

SAMPLE_APP_DATABASE_USER: "devuser"
SAMPLE_APP_DATABASE_PASSWORD: "devuser"

, . , database.yml

username: <%= ENV['SAMPLE_APP_DATABASE_USER'] %>
password: <%= ENV['SAMPLE_APP_DATABASE_PASSWORD'] %>

dotenv-rails

+1

Source: https://habr.com/ru/post/1659721/


All Articles