1.command,shell,raw,script模块的作用和区别
#: command可以在受管主机上执行shell命令,但是不支持环境变量和操作符,也无法使用管道符,并要求受管主机安装python;
shell模块调用的、bin/sh指令执行,要求在受管主机安装python;
raw不需要受管主机上安装python,直接使用远程shell运行命令,将结果返回给主控服务器;
#:command 模块的使用: 去执行一个脚本文件command.sh, command.sh文件的功能是echo "I amcommand module"
(1)首先去被控主机中去创建command.sh脚本:可以在所有被控主机创建,也可以指定哪个被控主机创建,我这里指定在node1主机中进行创建:
[root@rhces1 ~]# vim command.sh [root@rhces1 ~]# chmod +x command.sh [root@rhces1 ~]# ./command.sh I am command module [root@rhces1 ~]# cat command.sh #!/bin/bash echo "I am command module" [root@rhces1 ~]#
(2)在控制主机中执行command.sh脚本:
[root@rhce-128 ~]# ansible node -m command -a "bash /home/student/command.sh" node2.example.com | CHANGED | rc=0 >> I am command module node1.example.com | CHANGED | rc=0 >> I am command modual [root@rhce-128 ~]#
#:shell模块执行命令 ls /root | grep txt
[root@rhces1 ~]# touch file{1..2}.txt [root@rhces1 ~]# ls /root|grep txt file1.txt file2.txt [root@rhces1 ~]# ----------------------------------------------- [root@rhces2 ~]# touch file{1..2}.txt [root@rhces2 ~]# ls /root | grep txt file1.txt file2.txt [root@rhces2 ~]#
[root@rhce-128 ~]# ansible node -m shell -a "ls /root|grep txt chdir=/root" node2.example.com | CHANGED | rc=0 >> file1.txt file2.txt node1.example.com | CHANGED | rc=0 >> file1.txt file2.txt [root@rhce-128 ~]#
#:raw模块执行pwd命令
[root@rhce-128 ~]# ansible node -m raw -a "pwd" node2.example.com | CHANGED | rc=0 >> /root Shared connection to node2.example.com closed. node1.example.com | CHANGED | rc=0 >> /root Shared connection to node1.example.com closed. [root@rhce-128 ~]#
#:script模块执行 script.sh文件,文件的内容为 echo "I am script module"
[root@rhce-128 ~]# vim /root/script.sh [root@rhce-128 ~]# chmod +x script.sh [root@rhce-128 ~]# ansible node -m script -a "script.sh chdir=/root" node2.example.com | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to node2.example.com closed.\r\n", "stderr_lines": [ "Shared connection to node2.example.com closed." ], "stdout": " I am script module\r\n", "stdout_lines": [ " I am script module" ] } node1.example.com | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to node1.example.com closed.\r\n", "stderr_lines": [ "Shared connection to node1.example.com closed." ], "stdout": " I am script module\r\n", "stdout_lines&#