I'm a Rails beginner creating a portfolio in Ruby on Rails. Earlier, I implemented a simple image analysis using the Google Cloud Vision API in the following article.
Get data labels by linking with Google Cloud Vision API when previewing images with Rails
However, ** does not start well in heroku production environment ... (+ +) ** I knew that the authentication was probably not working well, but it took an unexpected amount of time to fix it, so I'll leave it as a memorandum.
I use git when I put various program files on heroku.
terminal
git push heroku master
In other words, it pushes the same information as github to heroku side. Since it is set not to upload files with key information to github (.gitignore), as a result, files with key information will not be uploaded to heroku. As a result, the json file with the service account key required for connecting with the Google cloud vision API was not put on heroku side either.
This time we will look at this method of passing information successfully.
What we're doing this time is passing it to heroku as an environment variable and calling it from there. Instead of putting the file itself on heroku's container, set the required key information in a variable.
Access heroku First, access the heroku screen and select the app you want to set.
Access Settings Click the tab in the screen, Settings
Click Reveal Config Vars Click the Reveal Config Vars button in Settings
Set environment variables
When you press the button of 3., the environment variables that have been set will appear, so a new one will appear there.
Copy and register GOOGLE_CREDENTIALS
(any character string is OK) and everything in the service account key file.
Restart heroku
After setting the environment variables, restart with heroku restart
We will also set the controller accordingly.
XXXX_controller.rb
:
#Vision API settings
if Rails.env.production?
config.credentials = JSON.parse(ENV.fetch('GOOGLE_CREDENTIALS'))
else
config.credentials = ENV["GOOGLE_APPLICATION_CREDENTIALS"]
end
:
This time, in the case of the production environment, get the environment variables set in heroku and Changed to set it in config as a JSON file.
Now you can use the Google Cloud Vision API on heroku!
Despite the simple settings, it took a long time ... Check heroku's log carefully, and if the log information is inadequate, You can see it by making the following settings and checking the detailed information. https://qiita.com/YujiNaito/items/3102ad59124d38433b2e
Also, I'm worried whether it is the correct answer to forcefully do it from this environment variable ... Is it OK for security? There seems to be a better way ... There is a better way than this! If you have any questions, please feel free to comment.
Recommended Posts