在Ansible中执行命令之前先查找文件 [英] Sourcing a file before executing commands in Ansible

查看:103
本文介绍了在Ansible中执行命令之前先查找文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我收到类似找不到源源/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.

使用 shell 代替command模块,它将执行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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆