Search code examples
bashshellansiblenvm

How to run a shell function as a command in Ansible?


I'm using nvm (https://github.com/creationix/nvm), which is essentially a shell script that you source into your shell and then call, for example, nvm install [version]. But no matter how I try and call that function, ansible can't seem to find it.

I've tried using the command and shell modules. I've tried using become and become_user. I've tried using sudo -iu like in https://github.com/leonidas/ansible-nvm/blob/master/tasks/main.yml, but it doesn't work for me. It must be possible though since it works in that file.

How can I run any shell function in Ansible? In this case I've got a source nvm.sh in my .zshrc which allows me to execute nvm commands from the interactive shell fine.


Solution

  • You'll need to use the shell module, because you want to run shell commands, and you'll need to source in the nvm script into that environment. Something like:

    - shell: |
        source /path/to/nvm
        nvm install ...
    

    Whether or not you use become depends on whether or not you want to run the commands as root (or another user).