Git post-receive hook not using ruby version specified by rbenv

Viewed 185

I'm deploying code to an ubuntu server which I've declared as a git remote with git push prod master.

But it's using the wrong version of Ruby.

Error

Bundler::RubyVersionMismatch: Your Ruby version is 2.7.0, but your Gemfile specified 2.7.1

Manually ssh'ing onto the server and running code, it shows the correct version of ruby.

$ rbenv local #=> 2.7.1
$ rbenv global #=> 2.7.1
$ ruby -v #=> ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-linux]

post-receive hook

#!/bin/bash

GIT_DIR=/home/me/appname_prod
WORK_TREE=/home/me/appname
export APPNAME_DATABASE_USER='appname'

export RAILS_ENV=production
. ~/.bash_profile

while read oldrev newrev ref
do
    if [[ $ref =~ .*/master$ ]];
    then
        echo "Master ref received.  Deploying master branch to production..."
        mkdir -p $WORK_TREE
        git --work-tree=$WORK_TREE --git-dir=$GIT_DIR checkout -f
        mkdir -p $WORK_TREE/shared/pids $WORK_TREE/shared/sockets $WORK_TREE/shared/log

        # start deploy tasks
        cd $WORK_TREE
        bundle install
        rake db:create
        rake db:migrate
        rake assets:precompile
        sudo restart puma-manager
        sudo service nginx restart
        # end deploy tasks
        echo "Git hooks deploy complete"
    else
        echo "Ref $ref successfully received.  Doing nothing: only the master branch may be deployed on this server."
    fi
done

.bash_profile

. ~/.bashrc

.bashrc

...
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

$ type rbenv returns

rbenv is a function
rbenv () 
{ 
    local command;
    command="${1:-}";
    if [ "$#" -gt 0 ]; then
        shift;
    fi;
    case "$command" in 
        rehash | shell)
            eval "$(rbenv "sh-$command" "$@")"
        ;;
        *)
            command rbenv "$command" "$@"
        ;;
    esac
}

I don't have a good understanding of code below the app level, so I'm not sure what is going wrong here.

Is there a way I might try to fix this?

2 Answers

I was struggling same problem some years ago but with cron.

I think your .bashrc needs some details. bundle and rake commands are rbenv shims, but you are not loading them in your path. .bashrc

export PATH="$HOME/.rbenv/shims:$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

and prefix your commands with shims path (I just took code from my crontab)

...
$HOME/.rbenv/shims/bundle install
$HOME/.rbenv/shims/rake db:create
$HOME/.rbenv/shims/rake db:migrate
$HOME/.rbenv/shims/rake assets:precompile
...

I solved this by simply loading rbenv in the post-receive hook, rather than in .bashrc.

# hooks/post-receive

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
Related