在 Ansible 中执行命令之前获取文件 [英] Sourcing a file before executing commands in Ansible
问题描述
我正在尝试使用以下 Ansible yml 文件使用 nvm 安装 node js 版本.
I am trying to install node js version using nvm using below Ansible yml file.
我收到错误,如未找到源source/home/centos/.nvm/nvm.sh"文件.但是如果我通过使用 ssh 登录机器来做同样的事情,那么它就可以正常工作.
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
错误:
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}
推荐答案
关于没有这样的文件"错误:
source
是一个内部 shell 命令(参见例如 Bash 内置命令),而不是可以运行的外部程序.您的系统中没有名为 source
的可执行文件,这就是您收到 No such file or directory
错误的原因.
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.
代替 command
模块使用 shell
将在 shell 中执行 source
命令.
Instead of the command
module use shell
which will execute the source
command inside a shell.
在 with_items
循环中,Ansible 将运行 shell 两次,并且两个进程将相互独立.在一个中设置的变量不会被另一个看到.
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.
您应该在一个 shell 进程中运行这两个命令,例如:
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
<小时>
其他备注:
在 git
任务中使用 {{ ansible_env.HOME }}
而不是 ~
.任何一个都可以在这里工作,但波浪号扩展是 shell 的功能,您正在为 Ansible 编写代码.
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.
这篇关于在 Ansible 中执行命令之前获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!