Install Bundler gem using Ansible

Since Ansible 1.3 following native solution is possible:

- name: requirements for installing gems
  apt:
    name: {{ item }}
  with_items:
    - ruby
    - ruby-dev
    - make

- name: install gem with proper $PATH
  gem:
    name: xyz
    user_install: no

Mention the user_install parameter! Additionally some dependecies installed by the bundler could need following further package dependencies:

  • zlib1g-dev

The problem is that, when running gem install bundler via ansible, you're not initializing rbenv properly, since rbenv init is run in .bashrc or .bash_profile. So the gem command used is the system one, not the one installed as a rbenv shim. So whenever you install a gem, it is installed system-wide, not in your rbenv environment.

To have rbenv initialized properly, you must execute bash itself and explicitely state that it's a login shell, so it reads it's initialization files :

ansible your_host -m command -a 'bash -lc "gem install bundler"' -u your_rbenv_user 

Leave the -u your_rbenv_user part if you really want to do this as root.

If the above command works, you can easily turn it into a playbook action :

- name: Install Bundler
  become_user: your_rbenv_user
  command: bash -lc "gem install bundler"

It's cumbersome, but it's the only way I found so far.


I've met the similar environment issue when I tried to run commands as another user. As mentioned in this feature request you have two options to execute your command in login shell (that will load user environment). For example i'ld like to install bundler as rails user:

- name: Install Bundler
  shell: gem install bundler
  sudo_user: rails -i

or

- name: Install Bundler
  command: sudo -iu rails gem install bundler