Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store a JSON file to an ENV variable with dotenv?

I am using Google Drive API with my Rails application. The API is working fine. I have the following client_secret.json file:

{
  "type": "service_account",
  "project_id": "gobirdie-landing-page",
  "private_key_id": "xxxxx",
  "private_key": "-----BEGIN PRIVATE KEY----- xxxxx -----END PRIVATE KEY-----\n",
  "client_email": "[email protected]",
  "client_id": "xxxxxxxxx",
  "auth_uri": "xxxxxx",
  "token_uri": "xxxxxxx": "xxxxxxxx": "xxxxxxxxx"
}

which is called in my controller

@session = GoogleDrive::Session.from_service_account_key("client_secret.json")

With this configuration no problem, I manage to use the API. However, I would like to store my JSON in the .env file like:

CLIENT_SECRET = "{
  "type": "service_account",
  "project_id": "gobirdie-landing-page",
  "private_key_id": "xxxxx",
  "private_key": "-----BEGIN PRIVATE KEY----- xxxxx -----END PRIVATE KEY-----\n",
  "client_email": "[email protected]",
  "client_id": "xxxxxxxxx",
  "auth_uri": "xxxxxx",
  "token_uri": "xxxxxxx": "xxxxxxxx": "xxxxxxxxx"
}" 

And call it in the controller in this way

@session = GoogleDrive::Session.from_service_account_key(ENV['CLIENT_SECRET'])

Or in this way

@session = GoogleDrive::Session.from_service_account_key(JSON.parse(ENV['CLIENT_SECRET']))

But neither methods are working. So my question is : "Is it possible to store JSON file in an ENV variable ?"

like image 648
Quentin P. Avatar asked May 23 '19 14:05

Quentin P.


People also ask

Can package JSON access environment variables?

You can use environment values to inject in your package. json like this: Any environment variables that start with npm_config_ will be interpreted as a configuration parameter.

What is env JSON?

The env. json file is a project-specific list of accessible variables. This file is the ideal place to store secret keys, project-wide properties, or anything else you want to obfuscate or share between your files.

Does dotenv override environment variables?

It seems like dotenv does not override variables if they are defined in the environment, by design: By default, it won't overwrite existing environment variables as dotenv assumes the deployment environment has more knowledge about configuration than the application does.


1 Answers

Convert the JSON object to string and store it in the ENV

You can use JSON.dump to convert JSON object to string

and then in your controller JSON.parse(ENV['CLIENT_SECRET'])

Alternatively

you can create a google_session.rb inside initializers folder

$google_session = GoogleDrive::Session.from_service_account_key(
   # config goes here
)

and in your controller you will have access to $google_session global variable

like image 146
PGill Avatar answered Sep 19 '22 17:09

PGill