Ansible - 命令模块

本文介绍了Ansible的命令模块,包括command、shell和raw。command模块用于执行系统命令,不支持shell特性;shell模块允许使用shell特性如管道;raw模块则在没有Python环境的主机上执行命令。每个模块都有其特定使用场景,如command更安全,shell支持更多shell特性,而raw适用于老旧或无Python环境的设备。

在之前的文章中,我们已经对 Ansible 以及 Ansible Adhoc 做了讲解,下面会对 Ansible 的常用模块进行讲解,主要包括 命令模块、文件处理模块、包管理模块、服务管理模块等。

今天就带大家熟悉一下 Ansible 的几个命令模块,包括:

  • command - 在远程节点上执行命令
  • shell - 让远程主机在 shell 进程下执行命令
  • raw - 在没有 Python 环境的主机上执行命令

command 模块

  • command 模块用于在给的的节点上运行系统命令,比如 echo hello。
  • 不是调用的 shell 的指令,所以没有 bash 的环境变量,也不能使用 shell 的一些操作方式,因此不支持像 $HOME 这样的变量,以及 <>|;& 等都是无效的。也就是在 command 模块中 无法使用管道符

模块参数

名称必选备注
chdirno运行 command 命令前先 cd 到这个目录
createsno如果这个参数对应的文件存在,就不运行 command
removesno如果这个参数对应的文件不存在,就不运行 command,与 creates 参数的作用相反

示例

  • 列出指定目录下的文件
# ansible test -m command -a "ls /root"
172.20.21.120 | SUCCESS | rc=0 >>
anaconda-ks.cfg
test.sh
whoami.rst
  • 根据指定文件是否存在判断是否执行
# ansible test -m command -a "ls /root creates=test.sh"
172.20.21.120 | SUCCESS | rc=0 >>
skipped, since test.sh exists

# ansible test -m command -a "ls /root removes=test.sh1"
172.20.21.120 | SUCCESS | rc=0 >>
skipped, since test.sh1 does not exist
  • 切换目录执行命令
# ansible test -m command -a "cat test.sh chdir=/root"
172.20.21.120 | SUCCESS | rc=0 >>
#!/bin/bash
i=0
echo $((i+1))

# ansible test -m command -a "sh test.sh chdir=/root"
172.20.21.120 | SUCCESS | rc=0 >>
1
  • 无法使用管道符
# ansible test -m command -a "ls /root | grep test"
172.20.21.120 | FAILED | rc=2 >>
/root:
anaconda-ks.cfg
test.sh
whoami.rstls: 无法访问|: 没有那个文件或目录
ls: 无法访问grep: 没有那个文件或目录
ls: 无法访问test: 没有那个文件或目录non-zero return code

shell模块

让远程主机在 shell 进程下执行命令,从而支持 shell 的特性,如管道等。与 command 模块几乎相同,但在执行命令的时候调用的是 /bin/sh

模块参数与 command 模块相同。

示例

  • 切换目录,执行命令并保持输出
# ansible test -m shell -a "sh test.sh > result chdir=/root"
172.20.21.120 | SUCCESS | rc=0 >>


# ansible test -m shell -a "cat result chdir=/root"
172.20.21.120 | SUCCESS | rc=0 >>
1

raw模块

简介

raw 模块不需要远程系统上的 Python。

raw 模块只适用于下列两种场景,第一种情况是在较老的(Python 2.4和之前的版本)主机上,另一种情况是对任何没有安装 Python 的设备(如路由器)。 在其他情况下,使用 shellcommand 模块更为合适。

示例

# ansible test -m raw -a "pwd"
172.20.21.120 | SUCCESS | rc=0 >>
/root
Shared connection to 172.20.21.120 closed.

区别

command,shell,raw 模块都是 ansible 远程执行命令的一种指令模式,但是它们的适用还是有一定的区别。

  1. command 模块不是调用的 shell 的指令,所以不能使用 bash 的环境变量,也不能使用 shell 的一些操作方式,其他和 shell 没有区别;另外,command 模块更安全,因为它不受用户环境变量的影响。
  2. shell 与 command 模块几乎相同,但在执行命令的时候使用的是 /bin/sh。从而支持 shell 的特性,如管道等。
  3. raw 很多地方和 shell 类似,更多的地方建议使用 shell 和 command 模块。但是如果是使用老版本 python,需要用到 raw,又或者是没有安装 python 模块的客户端,如路由器。

如果觉得有用,欢迎关注我的微信,有问题可以直接交流:

你的关注是对我最大的鼓励!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值