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

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


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


Here is my playbook for this:

- hosts: all  vars:    # https://github.com/nvm-sh/nvm/releases    nvm_version: "0.34.0"    # https://github.com/nodejs/node/releases    # "node" for latest version, "--lts" for latest long term support version,    # or provide a specific version, ex: "10.16.3"    node_version: "--lts"  tasks:  - name: Get_nvm_install_script | {{ role_name | basename }}    tags: Get_nvm_install_script    get_url:      url: https://raw.githubusercontent.com/nvm-sh/nvm/v{{ nvm_version }}/install.sh      dest: "{{ ansible_user_dir }}/nvm_install.sh"      force: true  - name: Install_or_update_nvm | {{ role_name | basename }}    tags: Install_or_update_nvm    command: bash {{ ansible_user_dir }}/nvm_install.sh  - name: Install_nodejs | {{ role_name | basename }}    tags: Install_nodejs    shell: |      source {{ ansible_user_dir }}/.nvm/nvm.sh      nvm install {{ node_version }}    args:      executable: /bin/bash

Note the use of executable: /bin/bash, as source command is not available in all shells, so we specify bash because it includes source

As an alternative to source you can use the dot:

  - name: Install_nodejs | {{ role_name | basename }}    tags: Install_nodejs    shell: |      . {{ ansible_user_dir }}/.nvm/nvm.sh      nvm install {{ node_version }}