在Ansible中执行命令之前获取文件

Nag*_*nan 13 ansible ansible-playbook

我正在尝试使用下面的Ansible yml文件使用nvm安装节点js版本.

我收到错误,如找不到源"home /home/centos/.nvm/nvm.sh"文件.但如果我通过使用ssh登录机器来做同样的事情,那么它可以正常工作.

- 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
Run Code Online (Sandbox Code Playgroud)

错误:

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}
Run Code Online (Sandbox Code Playgroud)

tec*_*raf 18

关于"没有这样的文件"错误:

source是一个内部shell命令(参见例如Bash Builtin命令),而不是您可以运行的外部程序.source您的系统中没有命名可执行文件,这就是您收到No such file or directory错误的原因.

而不是command使用shellsource在shell内执行命令的模块.


关于采购问题:

with_items循环中,Ansible将运行shell两次,并且两个进程将彼此独立.一个中设置的变量将不会被另一个看到.

您应该在一个shell进程中运行这两个命令,例如:

- name: Install node {{ nvm.node_version }}
  shell: "source /home/centos/.nvm/nvm.sh && nvm install {{ nvm.node_version }}"
  tags: nvm
Run Code Online (Sandbox Code Playgroud)

其他评论:

使用{{ ansible_env.HOME }}而不是~git任务中.任何一个都可以在这里工作,但代字号扩展是shell的功能,你正在为Ansible编写代码.

  • 也无法使用shell模块运行命令“ source / etc / environment”。 (2认同)
  • @PythonEnthusiast您应该使用`.`来替换`bin / sh`的`source`。 (2认同)