Search code examples
ruby-on-railscapistranocredentials

Rails credentials with environment on Capistrano task


I'm using Rails credentials to store secret data on my Rails 6 app. There are 3 environments (dev, staging, production).

When I run cap staging deploy:my_task task always uses default key path (config/master.key) and not config/environments/staging.key. I tried to pass it as variable but it did not work. Here is my task


task :my_task do
    on roles(:app), in: :sequence, wait: 5 do
      run_locally do
        with rails_env: fetch(:rails_env), rails_master_key: `cat config/credentials/#{fetch(:rails_env)}.key` do
          
          pp Rails.application.credentials
        end
      end
    end
  end

On pp Rails.application.credentials I got:

#<ActiveSupport::EncryptedConfiguration:0x00005640fe8cce28
@config={},
@content_path=
 #<Pathname:/builds/path/to/my/project/config/credentials.yml.enc>,
@env_key="RAILS_MASTER_KEY",
@key_file_contents=nil,
@key_path=
 #<Pathname:/builds/path/to/my/project/config/master.key>,
@options={},
@raise_if_missing_key=false>

What am I missing?


Solution

  • I finally choose the manual way. That's the only way I found.

    task :my_task do
        on roles(:app), in: :sequence, wait: 5 do
          run_locally do
            with rails_env: fetch(:rails_env) do
              env_path = "config/credentials/#{fetch(:rails_env)}"
              credentials = Rails.application.encrypted("#{env_path}.yml.enc",
                                              key_path: "#{env_path}.key").config
              pp credentials
          end
        end
      end
    end