How can I use Rails 5.2 credentials in capistrano's deploy.rb file?

血红的双手。 提交于 2019-12-05 08:10:22

1. Upload master.key the file on the server (user read-only) like so:

namespace :setup do
  desc "setup: copy config/master.key to shared/config"
  task :copy_linked_master_key do
    on roles(fetch(:setup_roles)) do
      sudo :mkdir, "-pv", shared_path
      upload! "config/master.key", "#{shared_path}/config/master.key"
      sudo :chmod, "600", "#{shared_path}/config/master.key"
    end
  end
  before "deploy:symlink:linked_files", "setup:copy_linked_master_key"
end

Put it in your lib/capistrano/tasks/setup.rake

2. Ensure file is linked

In deploy.rb:

set :linked_files, fetch(:linked_files, []).push("config/master.key")

3. Ensure Capfile loads the task:

Make sure your Capfile has the line

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }

I solved the problem as follows:

set :rollbar_token, YAML.load(`rails credentials:show`)['rollbar_token']

The way I solve this is to declare a $ROLLBAR_ACCESS_TOKEN environment variable on the server. I place it at the top of ~deployer/.bashrc like this:

export ROLLBAR_ACCESS_TOKEN=...

Then I integrate with Capistrano by defining this task:

task :set_rollbar_token do
  on release_roles(:all).first do
    set :rollbar_token, capture("echo $ROLLBAR_ACCESS_TOKEN").chomp
  end
end

before "rollbar:deploy", "set_rollbar_token"
require File.expand_path("./environment", __dir__)
puts App::Application.credentials.rollbar_token

Put the following line(s) on top of your config/deploy.rb

# config/deploy.rb
require File.expand_path("./environment", __dir__)

This include make constants like Rails.application accessible in files like config/deploy/production.rb. Now things like the following are possible:

# config/deploy/staging.rb
server "production.lan", user: "production", roles: %w{app db web}
set :stage, :production
set :branch, "development"
set :pg_password, Rails.application.credentials[:staging][:postgres][:password]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!