常用的命令类模块
- command模块
- shell模块
- script模块
command跟shell模块的区别
两个模块都是在远程服务器上去执⾏命令。
两个模块之间的区别
1、command模块是ad-hoc的默认模块,故在执⾏ad-hoc时,不指定模块的名字则默认使⽤此模块。
在使用command模块时,如果需要执行的命令中含有重定向、管道符等操作时,这些符号也会失效,比如”<“, “>”, “|”, “;” 和 “&” 这些符号,如果你需要这些功能,可以参考后面介绍的shell模块,还有一点需要注意,如果远程节点是windows操作系统,则需要使用win_command模块。
2、shell模块可以执⾏SHELL的内置命令和特性(⽐如管道符),而command模块不支持。
command模块
先编辑hosts文件,在此定义三个分组,其中web_servers跟db_servers是all_servers的子组,共两台受管主机。
$ vim /etc/ansible/hosts
all:
children:
all_servers:
children:
web_servers:
hosts:
10.154.0.111:
db_servers:
hosts:
10.154.0.112:
案例
1、在所有分组主机上执行ls命令
$ ansible all -m command -a 'ls'
2、chdir参数表示执行命令之前,会先进入到指定的目录中,如上命令表示查看root目录下的文件
$ ansible web_servers -m command -a "chdir=/root ls"
3、creates参数判断tz.py文件存在,就不执行echo命令
$ ansible web_servers -m command -a "creates=/root/tz.py echo 'tz.py is not exists'"
4、removes参数判断文件存在,才执行echo命令
$ ansible web_servers -m command -a "removes=/root/tz.py echo 'tz.py is exists'"
shell模块
先看案例,后续有参数说明。
1、进入tmp目录,将test写入到test.txt文件中,这里shell模块可以使用>符号
$ ansible db_servers -m shell -a "chdir=/tmp echo test > test.txt"
2、调用远程主机/bin/bash执行命令,定义TestNum变量,写入到test.txt文件中,使用cat查看test.txt文件内容
$ ansible db_servers -m shell -a \
'executable=/bin/bash TestNum=666 ; echo $TestNum >/tmp/test.txt | cat /tmp/test.txt'
script模块
顾名思义,是一个执行脚本的模块,需要注意的是脚本文件存在于ansible主机上,不需要手动拷贝到远程主机后再执行。
先来看看几个案例
1、进入受管主机的/opt目录,执行ansible主机中/script/test.sh脚本
$ ansible db_servers -m script -a "chdir=/opt /script/test.sh"
这里需要注意的是:进入的是受管主机的/opt目录,执行的是ansible主机/script/目录下的test.sh脚本。
2、如果受管主机不存在/opt/testfile文件,就执行脚本,存在则不执行
$ ansible db_servers -m script -a "creates=/opt/testfile /script/test.sh"
3、如果受管主机存在/opt/testfile文件,就执行脚本,不存在则不执行
$ ansible db_servers -m script -a "removes=/opt/testfile /script/test.sh"
模块常用参数
除executable参数为shell模块使用,其他参数这三个模块都可使用。
- free_form
必须参数,指定需要远程执行的命令,如上述案例中的ls,echo之类的命令,注意不能写成free_form=ls,这种写法是错误的。 - chdir
指定一个目录,在执行对应的命令之前,会先进入到chdir参数指定的目录中。 - creates
当指定的文件存在时,就不执行对应命令。 - removes
当指定的文件存在时,才执行对应命令。 - executable(shell模块)
默认情况下,shell模块会调用远程主机中的/bin/sh去执行对应的命令;但我们可以使用此参数指定某种类型的shell去执行对应的命令,指定shell文件时,需要使用绝对路径。