Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 426
user779159 Avatar asked Oct 24 '25 18:10

user779159


1 Answers

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).

like image 137
larsks Avatar answered Oct 26 '25 08:10

larsks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!