ansible使用script模块在受控机上执行脚本(ansible2.9.5)

一,ansible的script模块的用途

script 模块用来在远程主机上执行 ansible 管理主机上的脚本,

即:脚本一直存在于 ansible 管理主机本地,

不需要手动拷贝到远程主机后再执行

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,script模块的应用例子:

1,用脚本在受控机上切换目录并查看当前目录:

[liuhongdi@centos8 ~]$ vi /home/liuhongdi/ansible/chandpwd.sh

内容:

cd /data/web/think_www;
pwd;

执行:

[root@centos8 ~]# ansible yujian -m script -a '/home/liuhongdi/ansible/chandpwd.sh'

2,一个常用的例子:在受控机上发布git代码:

编写脚本

[liuhongdi@centos8 ~]$ vi /home/liuhongdi/ansible/gitpubwww.sh

内容:

cd /data/site/think_www;
echo "---------------------------------------git status:
";
git status;
echo "---------------------------------------git pull:
";
git pull origin master;
echo "---------------------------------------git status:
";
git status;

执行:

[root@centos8 ~]# ansible yujian -m script -a '/home/liuhongdi/ansible/gitpubwww.sh'  --become  --become-method=sudo --become-user=root

3,根据文件判断是否需要执行脚本?

creates参数 :使用此参数指定一个远程主机中的文件,当指定的文件存在时,就不执行对应脚本

removes参数 :使用此参数指定一个远程主机中的文件,当指定的文件不存在时,就不执行对应脚本

[root@centos8 ~]# ansible yujian -m script -a 'removes=/root/isgit.txt /home/liuhongdi/ansible/gitpubwww.sh'  --become  --become-method=sudo --become-user=root
121.122.123.47 | SKIPPED

因为删除文件不成功,所以不执行

[root@centos8 ~]# ansible yujian -m script -a 'creates=/root/isgit.txt /home/liuhongdi/ansible/gitpubwww.sh'  --become  --become-method=sudo --become-user=root
121.122.123.47 | CHANGED => {
    "changed": true,
...

因为文件可以创建,所以成功执行

三,查看ansible的版本

[root@centos8 liuhongdi]# ansible --version
ansible 2.9.5
原文地址:https://www.cnblogs.com/architectforest/p/12766206.html