bundler snippets

Running (and debugging) cronjobs with rbenv and bundler

Tagged rbenv, backup, cron, bundler  Languages bash

This snippet shows how to run a backup script (Backup gem) and how to debug cron in case it doesn't work.

This example uses bundler and rbenv to complicate things:

# Set the path to include rbenv
PATH=$PATH:/home/xxx/.rbenv/shims/:/home/xxx/.rbenv/bin/:/bin:/usr/bin/

# Debug cron environment...
*/1 * * * * /bin/bash -l -c '/bin/env > /tmp/cron-env.log'

# Run backup every 12 hours
* */12 * * * /bin/bash -l -c 'eval "$(rbenv init -)" && cd /var/www/xxx/current && bundle exec backup perform --trigger xxx -c config/backup.rb >> /tmp/backup.log 2>&1'

If backup fails, check /tmp/backup.log and/or /tmp/cron-env.log.

No "bundle exec"

Tagged bundler, bundle exec  Languages ruby

If RubyGems >= 2.2.0:

export RUBYGEMS_GEMDEPS=-

else:

https://github.com/mpapis/rubygems-bundler

Install missing gem executables with `bundle install`

Tagged bundler, rails, rubygems, ruby  Languages bash

When:

$ bundle exec cucumber

bundler: command not found: cucumber
Install missing gem executables with `bundle install`

Do:

$ rm .bundle/config # remove a broken bundler configuration
$ gem update --system # might help if rubygems is outdated / broken
$ gem update bundler # might help if bundler is outdated / broken
$ bundle install # dependency hell

Or, start using, e.g., golang, crystal, etc.

How to clean ENV variables when executing external commands with Open3

Tagged bundler, command, env, open3, popen3, security, shell  Languages ruby

Running commands with Open3#popen3 from, for example, a Rails application will give the command access to all ENV variables, including potential secrets.

Before running commands in you need to clean the ENV variables:

# Clean the ENV
def with_env(env)
  backup = ENV.to_hash
  ENV.replace(env)
  yield
ensure
  ENV.replace(backup)
end
# Set PWD, ENV, and options
pwd = '/Alset/YledoM/'
env = {
  'oLLEH' => 'DLROw',
  'RACK_ENV' => 'test',
  'PATH' => ENV['PATH']
}
options = {
  chdir: pwd
}
# The command to run
cmd = "bundle exec ruby script.rb"
# Prints a 'dirty' env
ENV.sort.to_h.each do |key, val|
  puts "#{key} => #{val}"
end
# Run the command with the given ENV
with_env(env) do
  Open3.popen3(env, cmd, options) do |stdin, stdout, stderr, wait_thr|
    # YXES
  end
  # Prints a clean env
  ENV.sort.to_h.each do |key, val|
    puts "#{key} => #{val}"
  end
end