简体   繁体   中英

Host Rails App in the Google Cloud App Engine and set Environment variables

I will host my RoR API-App in the Google App-Engine.

Everything works so far, but I have to store usernames, passwords and keys (eg Database user/password) in plain text in the app.yaml . this is just stupid, so I will never be able to push this to my git repo! Usually I store stuff like this in an env variable and use them in my application.

But I did not find a way to set or access env variables.

Is there a way or an alternative to do so?

I did it!

For local development, I just set my env as usual.

If the mode is Production I load them from the Google Datastore all key values pairs and set them as an env variable.

I do this in an Initializer, to do so just create a file in YourApp/config/initializers/ and put the code in it! Just Create new Entities copy the Kind name in the code and set your project id. As your App is hosted in Google it should have access to the datastore (You need to set the right in the IAM-Manager)

require "google/cloud/datastore"
# Load the enviroment variables from the google datastore!
if Rails.env == "production"

  data_store = Google::Cloud::Datastore.new(
      project_id: 'YOUR_PROJECT_ID'
  )

  query = data_store.query "YOUR_KIND_NAME"
  results = data_store.run query

  puts "Set custom env variables!"
  # Set each result as an env variable
  results[0].properties.to_h.each do |key, value|
    ENV[key]= value
  end

end

As mentioned in Best practices for managing credentials , you may use an environment variable pointing to credentials outside of the application's source code, such as Cloud Key Management Service . I also recommend to take a look at Secret management with Cloud KMS documentation which explains solutions when you choose a secret management.

You can access env variables in your config file, the erb syntax is supported.

For example:

production:
  database: <%= ENV['DB_HOST'] %>
  username: <%= ENV['DB_USER'] %>
  password: <%= ENV['DB_PASS'] %>

Now you just have to setup these env variables in the Google App Engine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM