Rails use of yml file - ruby-on-rails

My first doubt is what is the difference between yml and yaml. Which one I should use. Also I have to put my label in yml file and to load them. So I don't have any idea how to do that. Any example or tutorial for that will be very helpful.

Setting Rails environment variables. Using ENV variables in Rails, locally and with Heroku. Rails configuration and security with environment variables.
Environment Variables
Many applications require configuration of settings such as email account credentials or API keys for external services. You can pass local configuration settings to an application using environment variables.
Operating systems (Linux, Mac OS X, Windows) provide mechanisms to set local environment variables, as does Heroku and other deployment platforms. Here we show how to set local environment variables in the Unix shell. We also show two alternatives to set environment variables in your application without the Unix shell.
Gmail Example
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "example.com",
authentication: "plain",
enable_starttls_auto: true,
user_name: ENV["GMAIL_USERNAME"],
password: ENV["GMAIL_PASSWORD"]
}
You could “hardcode” your Gmail username and password into the file but that would expose it to everyone who has access to your git repository. Instead use the Ruby variable ENV["GMAIL_USERNAME"] to obtain an environment variable. The variable can be used anywhere in a Rails application. Ruby will replace ENV["GMAIL_USERNAME"] with an environment variable.
Option One: Set Unix Environment Variables
export GMAIL_USERNAME="myname#gmail.com"
Option Two: Use the Figaro Gem
This gives you the convenience of using the same variables in code
whether they are set by the Unix shell or the figaro gem’s
config/application.yml. Variables in the config/application.yml file
will override environment variables set in the Unix shell.
Use this syntax for setting different credentials in development,
test, or production environments:
**
HELLO: world
development:
HELLO: developers
production:
HELLO: users
**
In this case, ENV["HELLO"] will produce “developers” in development, “users” in production and “world” otherwise.
Option Three: Use a local_env.yml File
Create a file config/local_env.yml:
Hope this help your answer!!!

'yml' is the extension you would use for 'YAML' files, so there's no difference between them.
Loading a YAML file in Ruby is as simple as YAML.load_file( <filename> ): it will read the whole file as a normal Hash.
To convert back to yaml use the homonymous method to_yaml.
You can get started here or here

Related

How to set up and use Rails environment variables in production server?

I need to set up an environment variable for my rails app. Both in my local machine and in the production server. I read some tutorials on the internet but NONE has given the complete instruction on how to set and use these variable in the actual production server. I use digital ocean and linux server to host my rails app.
I have spent days trying to figure this out, but still haven't found a clear and complete instruction from setting the variables on my local machine -> push it to git repo -> set and use the variables in production server. So, hope somebody can help me here, thanks!
UPDATE:
This is how I currently setup the environment variables in my rails app by using figoro gem:
You can set system-wide environment variables in the /etc/rc.local file (which is executed when the system boots). If your Rails app is the sole user of the Linux system, that is a good place to store credentials such as API keys because there is no risk of including this file in a public Git repository, as it is outside the application directory. The secrets will only be vulnerable if the attacker gains shell access to your Linux server.
Set the environment variables within /etc/rc.local (do not include the <> characters):
export SOME_LOGIN=<username>
export SOME_PASS=<password>
To see the value of an environment variable, use one of the following commands in the Linux shell:
printenv MY_VAR
echo $MY_VAR
To access those environment variables within Rails, use the following syntax:
Inside .rb files or at the rails console
ENV['MY_VAR']
Inside .yml files:
<%= ENV['MY_VAR'] %>
For anyone still having this issue, figaro now has an easy method in setting the production variables in heroku. Just run:
$ figaro heroku:set -e production
ryzalyusoff.
For Unix
You can use LINUX ENV in rails application.
# .env
GITHUB_SECRET_KEY=SECRET
TWITTER_ACCESS_KEY=XXXXXXXXXXXX
# in rails code
puts ENV["TWITTER_ACCESS_KEY"] # => SECRET
Create .env files for local machine and your production server. Export environment variables like this(on server with ssh):
export GITHUB_SECRET_KEY="XXXXXXXXXXXXXXXXXX"
Anyway, storing keys in config - bad idea. Just add .env.example, others keys configs add to .gitignore. Goodluck.
Example with Rails
For Windows
Syntax
SET variable
SET variable=string
SET /A "variable=expression"
SET "variable="
SET /P variable=[promptString]
SET "
Key
variable : A new or existing environment variable name e.g. _num
string : A text string to assign to the variable.
expression : Arithmetic expression
Windows CMD
I believe we should not push a secret file on git.
To ignore such file use gitignore file and push other code on the git.
On the server side just copy the secret file and create a symlink for that file.
You can find demo here http://www.elabs.se/blog/57-handle-secret-credentials-in-ruby-on-rails
You can set your environment variables in production in the same way, you do it for local system. However, there are couple of gems, which make it easier to track and push to production. Have a look at figaro. This will help you in setting up and deployment of env vars.
You can do this with figaro gem
or in rails 4 there is a file named secret.yml in config folder where you can define your environment variables this file is by default in .gitignore file.For production you need to manually copy that file to server for security reason so that your sensitive information is not available to any one
First create your variable like:
MY_ENV_VAR="this is my var"
And then make it global:
export MY_ENV_VAR
You can check if the process succeeded with:
printenv
Or:
echo MY_ENV_VAR

Using Figaro and Secrets.yml to Manage Env Variables

I have a rails 4.1 app and I'm trying to organize my env variables. As of right now I have a secrets.yml file in my config/ folder. I also installed the figaro gem. My goal was to have all my env variables in the application.yml (not checked into git) file and then use the secrets.yml (checked into git) file to map the variables from appliation.yml to the application. When I print the files using Rails.application.secrets It just shows hashes that look like this:
:salesforce_username=>"ENV['SALESFORCE_USERNAME']"
None of my external services are working with this env variables setup. When I view the traces, the actually ENV['ACCOUNT_ID'] are being passed through in the requests like this:
v2/accounts/ENV['ACCOUNT_ID']/envelopes
In addition, I cannot access my env variables using Rails.application.secrets.account_id in my app.
secrets.yml
development:
account_id: <%= ENV['ACCOUNT_ID'] %>
aplication.yml
development:
ACCOUNT_ID: "123456"
application.rb
# preload tokens in application.yml to local ENV
config = YAML.load(File.read(File.expand_path('../application.yml', __FILE__)))
config.merge! config.fetch(Rails.env, {})
config.each do |key, value|
ENV[key] = value.to_s unless value.kind_of? Hash
end
The gem provides a generator:
$ rails generate figaro:install
The generator creates a config/application.yml file and modifies the .gitignore file to prevent the file from being checked into a git repository.
You can add environment variables as key/value pairs to config/application.yml:
GMAIL_USERNAME: Your_Username
The environment variables will be available anywhere in your application as ENV variables:
ENV["GMAIL_USERNAME"]
This gives you the convenience of using the same variables in code whether they are set by the Unix shell or the figaro gem’s config/application.yml. Variables in the config/application.yml file will override environment variables set in the Unix shell.
In tests or other situations where ENV variables might not be appropriate, you can access the configuration values as Figaro method calls:
Figaro.env.gmail_username
Use this syntax for setting different credentials in development, test, or production environments:
HELLO: world
development:
HELLO: developers
production:
HELLO: users
In this case, ENV["HELLO"] will produce “developers” in development, “users” in production and “world” otherwise.
You say the ENV variables are being "passed through in the requests", but when I look at your code snippets I think the variables aren't ever being detected as such in the first place.
If you want to inject a variable into a string, double-check that you are using the following format, especially the # and {}:
important_string = "v2/accounts/#{ENV['ACCOUNT_ID']}/envelopes"
On a more general note, if you're unsure what environment variables are being set in a given environment, the easiest way to double-check is to open up the Rails console and query ENV like so:
$ rails console
> puts ENV.keys # find out what ENV vars are set
=> (returns a long list of var names)
> puts ENV['DEVISE_PEPPER']
=> "067d793e8781fa02aebd36e239c7878bdc1403d6bcb7c380beac53189ff6366be"

ENV variables only available in production console, not in app -- Rails, Figaro Gem

I am using the figaro gem and have created an application.yml file with all of my variables as per the documentation. This application.yml file is located in a shared folder (I'm using capistrano) and is symlinked to config/application.yml within the current live app directory, however I can only access the variables in the rails console and not the app. My credentials are listed as follows (real details omitted):
Note: I have tried removing the "" speech marks and also prefixing this list with production: with each line having 2 spaces, not tabbed, and it doesn't solve anything. The permissions on the file are exactly the same, 777, as the databse.yml file which was implemented in the same way.
application.yml
FFMPEG_LOCATION: "/path/to/ffmpeg"
EMAIL_USERNAME: "me#gmail.com"
EMAIL_PASSWORD: "password"
S3_BUCKET: "my_bucket"
AWS_SECRET_KEY_ID: "my_secret_key"
AWS_ACCESS_KEY_ID: "my_access_key"
I can access these variables in the production console =>
Loading production environment (Rails 3.2.14)
irb(main):001:0> ENV["S3_BUCKET"]
=> "my-s3-bucket-name"
However they don't return anything in the app itself. I set my linux box up following Ryan's excellent Pro railscast episode http://railscasts.com/episodes/335-deploying-to-a-vps
How can I get these variables accessible in the app itself?
If anyone needs more code just shout.
EDIT
I removed the figaro gem implemented the yaml config shown in the following railscasts tutorial: http://railscasts.com/episodes/85-yaml-configuration-revised. I think this is effectively what the figaro gem was doing however instead of using ENV variables, the tutorial uses CONFIG[:variables] which seem to work great.
Per Comment:
Nginx runs as its own user, so the environment variables need to live in it's space. As a user when you log in and run console, you're accessing a different set of environment variables than the nginx user accesses.
You can do this if you choose by adding them to the nginx config in the main context. But it's probably easier to go with straight yaml and add your secret tokens to your yaml file.

Securely providing the database password in a Rails app

As you know, you MUST provide the correct database name, username, and password for the database in the config/database.yml file, or your Rails app will refuse to work.
In the default setup, your password is in plain text in the config/database.yml file. If your app is on a free GitHub repository, then your password is public information. This is not a viable option for a serious app. (It's OK for a tutorial exercise, provided that you don't use this password for anything else.)
I have a solution that has worked for me so far, but I'm wondering if there is something better. You can see my deployed example at https://github.com/jhsu802701/bsf .
What I do is set up the config/database.yml file to provide the username and password for the development environment programatically. For the development environment, I add commands to the config/database.yml script to acquire the development environment username (which is my regular username for the Debian Linux setup I use) and a blank password. (I give my username Postgres superuser privileges.) For the production environment, I add a command in the deployment script that acquires the username and password from files elsewhere on my account and writes this information to the config/database.yml file.
Is there a better solution?
Is there a Ruby gem that covers this? If not, I'm thinking of creating one.
The way that heroku does it, and a vast majority of other rails shops are with ENV variables
Export two variables to your environment,
export POSTGRES_USERNAME='username'
export POSTGRES_PASSWORD='password'
then in your database.yml file you can do
username: <%= ENV['POSTGRES_USERNAME'] %>
password: <%= ENV['POSTGRES_PASSWORD'] %>
This is how I make it work:
On terminal/cmd:
heroku config:set YOUR_DATABASE_PASSWORD=passywordy
Then, in /config/database.yml file;
production:
<<: *default
password: <%= ENV['YOUR_DATABASE_PASSWORD'] %>
(this password area is automatically generated when I used rails new my_app -d postgresql)
On other than heroku export you variables to system environment (linux) by typing in bash
export KEY=value
Then you can call it in Rails by ENV['KEY']
e.g.
in bash:
export CMS_DATABASE_PASSWORD=MySecurePassword
in secrets.yml:
password: <%= ENV['CMS_DATABASE_PASSWORD'] %>
Setting the environment variables as described in existing posts above, will only persist the environment variables for the duration of the current shell session.
To set the environment variables permanently, the export instruction(s) should be added to your shell config file. (Then run source ~/.bashrc to apply the changes to your current session)
TL;DR: If you're using BASH, add the export instruction(s) to ~/.bashrc.
While the above should suffice (if using BASH on most popular Linux distros), confidently identifying which config file to update for your shell can be quite tricky. The following post explains the reasons why and provides guidance on which config file to edit.
https://unix.stackexchange.com/questions/117467/how-to-permanently-set-environmental-variables

Ruby on Rails use of environment variables

I want to use in my code (in views as well) variables like:
ENV['SERVER_URL1']
And want them to be different for diffident environments (prod, dev, test)
Were and how should I set them up?
Is this (using ENV vars) a right way to configure application for different environments?
about ENV['SERVER_URL'] - is it a standard variable? When does it becomes available.
I tried to set in different parts of application (application.rb, development.rb)
ENV['SERVER_URL1'] = 'http://localhost:4000/'
but it seems not to work.
When using Rails 4.1+, the new and preferred way to set ENV variables is to use the config/secrets.yml file.
Here is an excerpt from the 4.1 release notes
The secrets added to this file are accessible via Rails.application.secrets. For example, with the following config/secrets.yml:
development:
secret_key_base: 3b7cd727ee24e8444053437c36cc66c3
some_api_key: SOMEKEY
Rails.application.secrets.some_api_key returns SOMEKEY in the development environment.
See the Upgrading Ruby on Rails guide on how to migrate existing applications to use this feature.
So you should set:
development:
SERVER_URL1: http://localhost:4000
production:
SERVER_URL1: http://my-domain.com

Resources