Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sourcing a file before executing commands in Ansible

I am trying to install node js version using nvm using below Ansible yml file.

I get error like source "source /home/centos/.nvm/nvm.sh" file not found. But if I do the same by logging into the machine using ssh then it works fine.

- name: Install nvm
  git: repo=https://github.com/creationix/nvm.git dest=~/.nvm version={{ nvm.version }}
  tags: nvm

- name: Source nvm in ~/.profile
  lineinfile: >
    dest=~/.profile
    line="source ~/.nvm/nvm.sh"
    create=yes
  tags: nvm

- name: Install node {{ nvm.node_version }}
  command: "{{ item }}"
  with_items:
     - "source /home/centos/.nvm/nvm.sh"
     - nvm install {{ nvm.node_version }}
  tags: nvm

Error:

failed: [172.29.4.71] (item=source /home/centos/.nvm/nvm.sh) => {"cmd": "source /home/centos/.nvm/nvm.sh", "failed": true, "item": "source /home/centos/.nvm/nvm.sh", "msg": "[Errno 2] No such file or directory", "rc": 2}

failed: [172.29.4.71] (item=nvm install 6.2.0) => {"cmd": "nvm install 6.2.0", "failed": true, "item": "nvm install 6.2.0", "msg": "[Errno 2] No such file or directory", "rc": 2}
like image 974
Naggappan Ramukannan Avatar asked Dec 29 '16 11:12

Naggappan Ramukannan


People also ask

What is Ansible source?

source is an internal shell command (see for example Bash Builtin Commands), not an external program which you can run. There is no executable named source in your system and that's why you get No such file or directory error. Instead of the command module use shell which will execute the source command inside a shell.

How do you capture command output in Ansible?

To capture the output, you need to specify your own variable into which the output will be saved. To achieve this, we use the 'register' parameter to record the output to a variable. Then use the 'debug' module to display the variable's content to standard out.


1 Answers

Regarding the "no such file" error:

source is an internal shell command (see for example Bash Builtin Commands), not an external program which you can run. There is no executable named source in your system and that's why you get No such file or directory error.

Instead of the command module use shell which will execute the source command inside a shell.


Regarding the sourcing problem:

In a with_items loop Ansible will run the shell twice and both processes will be independent of each other. Variables set in one will not be seen by the other.

You should run the two commands in one shell process, for example with:

- name: Install node {{ nvm.node_version }}
  shell: "source /home/centos/.nvm/nvm.sh && nvm install {{ nvm.node_version }}"
  tags: nvm

Other remarks:

Use {{ ansible_env.HOME }} instead of ~ in the git task. Either one will work here, but tilde expansion is the functionality of shell and you are writing code for Ansible.

like image 169
techraf Avatar answered Oct 22 '22 12:10

techraf