ansible之二:模块用法

一:ansible远程执行命令

[root@ansible ~]# ansible test -m shell -a "date"
192.168.0.28 | SUCCESS | rc=0 >>
2016年 08月 02日 星期二 15:06:21 CST

[root@ansible ~]# ansible test -m raw -a "date"
192.168.0.28 | SUCCESS | rc=0 >>
2016年 08月 02日 星期二 15:06:21 CST
[root@ansible ~]# ansible test -m command -a "date" 
192.168.0.28 | SUCCESS | rc=0 >>
2016年 08月 02日 星期二
15:08:06 CST

test为主机组名 -m后面跟模块名 -a后面跟命令 ,shell raw模块支持管道 command模块不支持

二:ansible拷贝文件或目录

[root@ansible ~]# ansible test -m copy -a "src=/data/shell/ dest=/data/shell/ "
192.168.0.28 | SUCCESS => {
    "changed": true, 
    "dest": "/data/shell/", 
    "src": "/data/shell"
}

三:ansible远程执行脚本

首先创建一个shell脚本

vim  /tmp/test.sh  //加入内容

#!/bin/bash

echo `date` > /tmp/ansible_test.txt

然后把该脚本分发到各个机器上

ansible test -m copy -a "src=/tmp/test.sh dest=/tmp/test.sh mod=0755"

最后是批量执行该shell脚本

ansible test -m shell -a "/tmp/test.sh"

shell模块,还支持远程执行命令并且带管道 ansible test-m shell -a "cat /etc/passwd|wc -l "

四:ansible安装rpm包/管理服务

[root@ansible ~]# ansible test -m yum -a "name=glances state=installed"  //这里的name是centos系统里的服务名。
192.168.0.28 | SUCCESS => {
    "changed": true, 

五:ansible 同步模块synchronize 使用

功能: 数据同步管理  使用此模块需要服务端与web组都安装了rsync.

#ansible test -m shell -a "rpm -qa rsync"   检查是否安装了rsync

192.168.0.28 | SUCCESS | rc=0 >>

rsync-3.0.9-17.el7.x86_64

安装rsync

#ansible test -m shell -a "yum install -y rsync"

同步目录:

#ansible test -m synchronize -a "src=/data/adminshell/ dest=/data/adminshell/ "

同步目录,删除目的目录中源目录中没有的文件

#ansible test -m synchronize -a "src=/data/adminshell/ dest=/data/adminshell/ delete=yes"

"msg": "*deleting   test.txt "

同步目录,排除某个文件

ansible test -m synchronize -a "src=/data/adminshell/ dest=/data/adminshell/ rsync_opts="--exclude=exclude.txt" "

同步目录,排除多个文件

ansible test -m synchronize -a "src=/data/adminshell/ dest=/data/adminshell/ rsync_opts="--exclude=*.conf,--exclude=*.html,--exclude=test1" "

#ansible-doc -s synchronize   模块用法

 六:ping模块,检测主机是否存活。

[root@ansible ~]# ansible test -m ping     //如果ansible 后面跟all ,则表示检测 hosts 文件中所有的服务器是否存活!
192.168.0.28 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
原文地址:https://www.cnblogs.com/chenjiahe/p/5729520.html