ansible shell 使用问题

用ansible 执行如下shell 命令,显示启动成功,但是我到目标主机查看却是没有启动(有点不理解为什么)

img

img

然后我直接到目标主机手动执行,可以启动,有点怪,为什么ansible 不行

img

然后我在运维主机使用service 启动,居然启动成功

img

img

而用shell 模块,控制机显示成功,但是目标主机上还是没有启动

img

img

如果你使用 Ansible 执行 shell 命令,但是却没有在目标主机上看到期望的结果,那么可能是因为以下原因之一:

  1. 你的 shell 命令写错了,导致执行失败。建议检查你的命令是否有语法错误,并确保命令的路径正确。
  2. 你的 shell 命令依赖于环境变量,但是 ansible 执行命令时并没有设置这些变量。建议使用 ansible 的 environment 变量来设置环境变量。
  3. 你的 shell 命令依赖于一些文件或目录,但是这些文件或目录在目标主机上并不存在。建议使用 ansible 的 copy 模块将这些文件或目录拷贝到目标主机上。
  4. 你的 shell 命令依赖于一些软件包,但是这些软件包在目标主机上没有安装。建议使用 ansible 的 package 模块安装这些软件包。
  5. 你的 shell 命令需要使用 root 权限执行,但是 ansible 并没有以 root 身份执行命令。建议使用 ansible的 become 变量来以 root 身份执行命令。例如:
- name: run a command as root
  shell: /path/to/command
  become: yes

另外,如果你使用的是 ansible 的 command 模块,而不是 shell 模块,你可以使用 executable 变量来指定执行命令的 shell。例如:

- name: run a command as root
  command: /path/to/command
  become: yes
  executable: /bin/bash

还有,如果你使用的是 ansible 的 shell 模块,你可以使用 args 变量来传递参数给 shell。例如:

- name: run a command as root
  shell: /path/to/command
  args:
    chdir: /path/to/working/directory
    executable: /bin/bash
  become: yes

希望这些建议能帮助你解决你的问题。

用ansible来控制服务的启停的话,建议你还是编写好启动脚本,用script模块去运行。
因为shell模块在日常使用中,只适合基本命令操作各种,期间如果涉及管道符,环境变量的调用,很多时候都会有问题的。