• ansible 常用模块


    1)主机连通性测试

    [root@localhost ansible]# cat hosts |grep -v ^#|grep -v ^$
    [webservers]
    192.168.1.223
    192.168.1.221

    我们使用ansible web -m ping命令来进行主机连通性测试,效果如下:

    [root@localhost ansible]# ansible webservers -m ping
    192.168.1.221 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "ping": "pong"
    }
    192.168.1.223 | SUCCESS => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false, 
        "ping": "pong"
    }

    这样就说明我们的主机是连通状态的。接下来的操作才可以正常进行。

    2)command 模块

    [root@localhost ansible]# ansible webservers -m command -a 'ss -ntl'
    192.168.1.221 | CHANGED | rc=0 >>
    State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
    LISTEN     0      128          *:22                       *:*                  
    LISTEN     0      100    127.0.0.1:25                       *:*                  
    LISTEN     0      128         :::22                      :::*                  
    LISTEN     0      100        ::1:25                      :::*                  
    192.168.1.223 | CHANGED | rc=0 >>
    State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
    LISTEN     0      128          *:22                       *:*                  
    LISTEN     0      100    127.0.0.1:25                       *:*                  
    LISTEN     0      128         :::22                      :::*                  
    LISTEN     0      100        ::1:25                      :::*                  
    LISTEN     0      80          :::3306                    :::*  

    命令模块接受命令名称,后面是空格分隔的列表参数。给定的命令将在所有选定的节点上执行。它不会通过shell进行处理,比如$HOME和操作如"<",">","|",";","&" 工作(需要使用(shell)模块实现这些功能)。注意,该命令不支持| 管道命令
      下面来看一看该模块下常用的几个命令:

    chdir       # 在执行命令之前,先切换到该目录
    executable # 切换shell来执行命令,需要使用命令的绝对路径
    free_form   # 要执行的Linux指令,一般使用Ansible的-a参数代替。
    creates  # 一个文件名,当这个文件存在,则该命令不执行,可以
    用来做判断
    removes # 一个文件名,这个文件不存在,则该命令不执行

    下面我们来看看这些命令的执行效果:

    [root@localhost ansible]# ansible webservers -m command -a 'chdir=/root/ ls'    #先切换到/data/ 目录,再执行“ls”命令
    192.168.1.221 | CHANGED | rc=0 >>
    anaconda-ks.cfg
    192.168.1.223 | CHANGED | rc=0 >>
    10.sql
    1.sql
    4.sql
    a_mysql0_2020-01-16.sql02.gz
    a_mysql_2020-01-16.sql.gz
    anaconda-ks.cfg
    backup
    mingongge_bak.sql
    mysql-community-release-el7-5.noarch.rpm
    percona-xtrabackup-2.4.7-Linux-x86_64
    percona-xtrabackup-2.4.7-Linux-x86_64.tar.gz
    [root@localhost ~]# ansible webserver -m command -a 'creates=/root/aaa.jpg ls'    #如果/root/aaa.jpg存在,则不执行“ls”命令
    [WARNING]: Could not match supplied host pattern, ignoring: webserver
    [WARNING]: No hosts matched, nothing to do
    [root@localhost ~]# ansible webservers -m command -a 'removes=/root/aaa.jpg cat /root/a'  #如果/data/aaa.jpg存在,则执行“cat /data/a”命令
    192.168.1.221 | CHANGED | rc=0 >>
    
    192.168.1.223 | CHANGED | rc=0 >>
    
    [root@localhost ~]# 

    3)shell 模块

    shell模块可以在远程主机上调用shell解释器运行命令,支持shell的各种功能,例如管道等。

    这个模块用于将文件复制到远程主机,同时支持给定内容生成文件和修改权限等。
      其相关选项如下:

    src    #被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"
    content   #用于替换"src",可以直接指定文件的值
    dest    #必选项,将源文件复制到的远程主机的绝对路径
    backup   #当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息
    directory_mode    #递归设定目录的权限,默认为系统默认权限
    force    #当目标主机包含该文件,但内容不同时,设为"yes",表示强制覆盖;设为"no",表示目标主机的目标位置不存在该文件才复制。默认为"yes"
    others    #所有的 file 模块中的选项可以在这里使用

    用法举例如下:
    ① 复制文件:

    [root@localhost ~]# ansible webservers -m copy -a 'src=/etc/fstab dest=/root/fstab'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "checksum": "d265038d261fbc05a186fb5b51a6f88104bf5a4e", 
        "dest": "/root/fstab", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "f814419cfabc31ec2c045abfd74bf36a", 
        "mode": "0644", 
        "owner": "root", 
        "size": 465, 
        "src": "/root/.ansible/tmp/ansible-tmp-1579228850.76-172106291812409/source", 
        "state": "file", 
        "uid": 0
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "checksum": "d265038d261fbc05a186fb5b51a6f88104bf5a4e", 
        "dest": "/root/fstab", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "f814419cfabc31ec2c045abfd74bf36a", 
        "mode": "0644", 
        "owner": "root", 
        "size": 465, 
        "src": "/root/.ansible/tmp/ansible-tmp-1579228850.73-239212718197228/source", 
        "state": "file", 
        "uid": 0
    }

    ② 给定内容生成文件,并制定权限

    [root@localhost ~]#  ansible webservers -m copy -a 'content="I am keer
    " dest=/root/ljj.txt mode=666'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "checksum": "0421570938940ea784f9d8598dab87f07685b968", 
        "dest": "/root/ljj.txt", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "497fa8386590a5fc89090725b07f175c", 
        "mode": "0666", 
        "owner": "root", 
        "size": 10, 
        "src": "/root/.ansible/tmp/ansible-tmp-1579228935.37-220505593867428/source", 
        "state": "file", 
        "uid": 0
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "checksum": "0421570938940ea784f9d8598dab87f07685b968", 
        "dest": "/root/ljj.txt", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "497fa8386590a5fc89090725b07f175c", 
        "mode": "0666", 
        "owner": "root", 
        "size": 10, 
        "src": "/root/.ansible/tmp/ansible-tmp-1579228935.37-278506941965905/source", 
        "state": "file", 
        "uid": 0
    }

    我们现在可以去查看一下我们生成的文件及其权限:

    [root@localhost ~]# ansible webservers -m shell -a 'ls -l /root/ljj.txt'
    192.168.1.221 | CHANGED | rc=0 >>
    -rw-rw-rw- 1 root root 10 1月  17 10:42 /root/ljj.txt
    192.168.1.223 | CHANGED | rc=0 >>
    -rw-rw-rw- 1 root root 10 1月  17 10:42 /root/ljj.txt

    可以看出我们的ljj.txt文件已经生成,并且权限为666。

    ③ 关于覆盖
      我们把文件的内容修改一下,然后选择覆盖备份:

    [root@localhost ~]# ansible webservers -m copy -a 'content="I am keerya
    " backup=yes dest=/root/ljj.txt mode=666'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "backup_file": "/root/ljj.txt.2031.2020-01-17@10:45:26~", 
        "changed": true, 
        "checksum": "064a68908ab9971ee85dbc08ea038387598e3778", 
        "dest": "/root/ljj.txt", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "8ca7c11385856155af52e560f608891c", 
        "mode": "0666", 
        "owner": "root", 
        "size": 12, 
        "src": "/root/.ansible/tmp/ansible-tmp-1579229124.15-218967695281776/source", 
        "state": "file", 
        "uid": 0
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "backup_file": "/root/ljj.txt.51754.2020-01-17@10:45:26~", 
        "changed": true, 
        "checksum": "064a68908ab9971ee85dbc08ea038387598e3778", 
        "dest": "/root/ljj.txt", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "8ca7c11385856155af52e560f608891c", 
        "mode": "0666", 
        "owner": "root", 
        "size": 12, 
        "src": "/root/.ansible/tmp/ansible-tmp-1579229124.14-266503506198407/source", 
        "state": "file", 
        "uid": 0
    }

    现在我们可以去查看一下:

    [root@localhost ~]# ansible webservers -m shell -a 'ls -l /root/ljj.*'
    192.168.1.221 | CHANGED | rc=0 >>
    -rw-rw-rw- 1 root root 12 1月 17 10:45 /root/ljj.txt
    -rw-rw-rw- 1 root root 10 1月 17 10:42 /root/ljj.txt.2031.2020-01-17@10:45:26~
    192.168.1.223 | CHANGED | rc=0 >>
    -rw-rw-rw- 1 root root 12 1月 17 10:45 /root/ljj.txt
    -rw-rw-rw- 1 root root 10 1月 17 10:42 /root/ljj.txt.51754.2020-01-17@10:45:26~

    可以看出,我们的源文件已经被备份,我们还可以查看一下ljj.txt文件的内容:

    [root@localhost ~]# ansible webservers -m shell -a 'cat /root/ljj.txt'
    192.168.1.221 | CHANGED | rc=0 >>
    I am keerya
    192.168.1.223 | CHANGED | rc=0 >>
    I am keerya

    证明,这正是我们新导入的文件的内容。

    5)file 模块

      该模块主要用于设置文件的属性,比如创建文件、创建链接文件、删除文件等。
      下面是一些常见的命令:

    force  #需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
    group  #定义文件/目录的属组。后面可以加上mode:定义文件/目录的权限
    owner  #定义文件/目录的属主。后面必须跟上path:定义文件/目录的路径
    recurse  #递归设置文件的属性,只对目录有效,后面跟上src:被链接的源文件路径,只应用于state=link的情况
    dest  #被链接到的路径,只应用于state=link的情况
    state  #状态,有以下选项:
    
    directory:如果目录不存在,就创建目录
    file:即使文件不存在,也不会被创建
    link:创建软链接
    hard:创建硬链接
    touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
    absent:删除目录、文件或者取消链接文件

    ① 创建目录:

    [root@localhost ~]# ansible webservers -m file -a 'path=/data/app state=directory'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "gid": 0, 
        "group": "root", 
        "mode": "0755", 
        "owner": "root", 
        "path": "/data/app", 
        "size": 6, 
        "state": "directory", 
        "uid": 0
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "gid": 0, 
        "group": "root", 
        "mode": "0755", 
        "owner": "root", 
        "path": "/data/app", 
        "size": 6, 
        "state": "directory", 
        "uid": 0
    }
    [root@localhost ~]# ansible webservers -m shell -a 'ls -l /data'
    192.168.1.221 | CHANGED | rc=0 >>
    总用量 0
    drwxr-xr-x 2 root root  6 1月  17 10:50 app
    drwxr-xr-x 3 root root 18 1月  14 10:05 k8s
    192.168.1.223 | CHANGED | rc=0 >>
    总用量 0
    drwxr-xr-x 2 root root 6 1月  17 10:50 app

    ② 创建链接文件

    [root@localhost ~]# ansible webservers -m file -a 'path=/data/bbb.jpg src=/root/aaa.jpg state=link'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "dest": "/data/bbb.jpg", 
        "gid": 0, 
        "group": "root", 
        "mode": "0777", 
        "owner": "root", 
        "size": 13, 
        "src": "/root/aaa.jpg", 
        "state": "link", 
        "uid": 0
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "dest": "/data/bbb.jpg", 
        "gid": 0, 
        "group": "root", 
        "mode": "0777", 
        "owner": "root", 
        "size": 13, 
        "src": "/root/aaa.jpg", 
        "state": "link", 
        "uid": 0
    }
    [root@localhost ~]# ansible webservers -m shell -a 'ls -l /data'
    192.168.1.221 | CHANGED | rc=0 >>
    总用量 0
    drwxr-xr-x 2 root root  6 1月  17 10:50 app
    lrwxrwxrwx 1 root root 13 1月  17 10:53 bbb.jpg -> /root/aaa.jpg
    drwxr-xr-x 3 root root 18 1月  14 10:05 k8s
    192.168.1.223 | CHANGED | rc=0 >>
    总用量 0
    drwxr-xr-x 2 root root  6 1月  17 10:50 app
    lrwxrwxrwx 1 root root 13 1月  17 10:53 bbb.jpg -> /root/aaa.jpg

    ③ 删除文件

    [root@localhost ~]# ansible webservers -m file -a 'path=/root/a state=absent'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "path": "/root/a", 
        "state": "absent"
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "path": "/root/a", 
        "state": "absent"
    }
    [root@localhost ~]# ansible webservers -m shell -a 'ls /root/a'
    192.168.1.221 | FAILED | rc=2 >>
    ls: 无法访问/root/a: 没有那个文件或目录non-zero return code
    192.168.1.223 | FAILED | rc=2 >>
    ls: 无法访问/root/a: 没有那个文件或目录non-zero return code

    6)fetch 模块

    该模块用于从远程某主机获取(复制)文件到本地。
      有两个选项:
    dest:用来存放文件的目录
    src:在远程拉取的文件,并且必须是一个file,不能是目录
    [root@localhost ~]# ansible webservers -m fetch -a 'src=/data/bbb.jpg dest=/data'
    192.168.1.223 | CHANGED => {
        "changed": true, 
        "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
        "dest": "/data/192.168.1.223/data/bbb.jpg", 
        "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
        "remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
        "remote_md5sum": null
    }
    192.168.1.221 | CHANGED => {
        "changed": true, 
        "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
        "dest": "/data/192.168.1.221/data/bbb.jpg", 
        "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
        "remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
        "remote_md5sum": null
    }
    [root@localhost ~]# cd /data/
    [root@localhost data]# ls
    192.168.1.221  192.168.1.223
    [root@localhost data]# ls 192.168.1.223/data/bbb.jpg 
    192.168.1.223/data/bbb.jpg
    [root@localhost data]# ls 192.168.1.221/data/bbb.jpg 
    192.168.1.221/data/bbb.jpg

    7)cron 模块

      该模块适用于管理cron计划任务的。
      其使用的语法跟我们的crontab文件中的语法一致,同时,可以指定以下选项:

    day= #日应该运行的工作( 1-31, , /2, )
    hour= # 小时 ( 0-23, , /2, )
    minute= #分钟( 0-59, , /2, )
    month= # 月( 1-12, *, /2, )
    weekday= # 周 ( 0-6 for Sunday-Saturday,, )
    job= #指明运行的命令是什么
    name= #定时任务描述
    reboot # 任务在重启时运行,不建议使用,建议使用special_time
    special_time #特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
    state #指定状态,present表示添加定时任务,也是默认设置,absent表示删除定时任务
    user # 以哪个用户的身份执行

    ① 添加计划任务

    [root@localhost ~]# ansible webservers -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 172.17.0.1 &> /dev/null"'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "envs": [], 
        "jobs": [
            "ntp update every 5 min"
        ]
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "envs": [], 
        "jobs": [
            "ntp update every 5 min"
        ]
    }
    [root@localhost ~]# ansible webservers -m shell -a 'crontab -l'
    192.168.1.223 | CHANGED | rc=0 >>
    #Ansible: ntp update every 5 min
    */5 * * * * /sbin/ntpdate 172.17.0.1 &> /dev/null
    192.168.1.221 | CHANGED | rc=0 >>
    #Ansible: ntp update every 5 min
    */5 * * * * /sbin/ntpdate 172.17.0.1 &> /dev/null

    可以看出,我们的计划任务已经设置成功了。

    ② 删除计划任务
      如果我们的计划任务添加错误,想要删除的话,则执行以下操作:
      首先我们查看一下现有的计划任务:

    [root@localhost ~]# ansible webservers -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 172.17.0.1 &> /dev/null" state=absent'
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "envs": [], 
        "jobs": []
    }
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "envs": [], 
        "jobs": []
    }
    [root@localhost ~]# ansible webservers -m shell -a 'crontab -l'
    192.168.1.221 | CHANGED | rc=0 >>
    
    192.168.1.223 | CHANGED | rc=0 >>
    
    [root@localhost ~]# 

    8)yum 模块

    顾名思义,该模块主要用于软件的安装。
      其选项如下:

    name=  #所安装的包的名称
    state=  #present--->安装, latest--->安装最新的, absent---> 卸载软件。
    update_cache  #强制更新yum的缓存
    conf_file  #指定远程yum安装时所依赖的配置文件(安装本地已有的包)。
    disable_pgp_check  #是否禁止GPG checking,只用于presentor latest。
    disablerepo  #临时禁止使用yum库。 只用于安装或更新时。
    enablerepo  #临时使用的yum库。只用于安装或更新时。

     下面我们就来安装一个包试试看:

    [root@localhost ~]# ansible webservers -m yum -a 'name=httpd state=present'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "changes": {
            "installed": [
                "httpd"
            ]
        }, 
        "msg": "", 
        "rc": 0, 
        "results": [
            "Loaded plugins: fastestmirror
    Loading mirror speeds from cached hostfile
     * base: mirrors.ustc.edu.cn
     * extras: mirrors.ustc.edu.cn
     * updates: mirrors.ustc.edu.cn
    Resolving Dependencies
    --> Running transaction check
    ---> Package httpd.x86_64 0:2.4.6-90.el7.centos will be installed
    --> Processing Dependency: httpd-tools = 2.4.6-90.el7.centos for package: httpd-2.4.6-90.el7.centos.x86_64
    --> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-90.el7.centos.x86_64
    --> Processing Dependency: libaprutil-1.so.0()(64bit) for package: httpd-2.4.6-90.el7.centos.x86_64
    --> Processing Dependency: libapr-1.so.0()(64bit) for package: httpd-2.4.6-90.el7.centos.x86_64
    --> Running transaction check
    ---> Package apr.x86_64 0:1.4.8-5.el7 will be installed
    ---> Package apr-util.x86_64 0:1.5.2-6.el7 will be installed
    ---> Package httpd-tools.x86_64 0:2.4.6-90.el7.centos will be installed
    ---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ================================================================================
     Package            Arch          Version                     Repository   Size
    ================================================================================
    Installing:
     httpd              x86_64        2.4.6-90.el7.centos         base        2.7 M
    Installing for dependencies:
     apr                x86_64        1.4.8-5.el7                 base        103 k
     apr-util           x86_64        1.5.2-6.el7                 base         92 k
     httpd-tools        x86_64        2.4.6-90.el7.centos         base         91 k
     mailcap            noarch        2.1.41-2.el7                base         31 k
    
    Transaction Summary
    ================================================================================
    Install  1 Package (+4 Dependent packages)
    
    Total download size: 3.0 M
    Installed size: 10 M
    Downloading packages:
    --------------------------------------------------------------------------------
    Total                                              593 kB/s | 3.0 MB  00:05     
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : apr-1.4.8-5.el7.x86_64                                       1/5 
      Installing : apr-util-1.5.2-6.el7.x86_64                                  2/5 
      Installing : httpd-tools-2.4.6-90.el7.centos.x86_64                       3/5 
      Installing : mailcap-2.1.41-2.el7.noarch                                  4/5 
      Installing : httpd-2.4.6-90.el7.centos.x86_64                             5/5 
      Verifying  : apr-1.4.8-5.el7.x86_64                                       1/5 
      Verifying  : mailcap-2.1.41-2.el7.noarch                                  2/5 
      Verifying  : httpd-tools-2.4.6-90.el7.centos.x86_64                       3/5 
      Verifying  : apr-util-1.5.2-6.el7.x86_64                                  4/5 
      Verifying  : httpd-2.4.6-90.el7.centos.x86_64                             5/5 
    
    Installed:
      httpd.x86_64 0:2.4.6-90.el7.centos                                            
    
    Dependency Installed:
      apr.x86_64 0:1.4.8-5.el7                     apr-util.x86_64 0:1.5.2-6.el7    
      httpd-tools.x86_64 0:2.4.6-90.el7.centos     mailcap.noarch 0:2.1.41-2.el7    
    
    Complete!
    "
        ]
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "changes": {
            "installed": [
                "httpd"
            ]
        }, 
        "msg": "", 
        "rc": 0, 
        "results": [
            "Loaded plugins: fastestmirror
    Loading mirror speeds from cached hostfile
     * base: mirror01.idc.hinet.net
     * extras: mirror01.idc.hinet.net
     * updates: mirror01.idc.hinet.net
    Resolving Dependencies
    --> Running transaction check
    ---> Package httpd.x86_64 0:2.4.6-90.el7.centos will be installed
    --> Processing Dependency: httpd-tools = 2.4.6-90.el7.centos for package: httpd-2.4.6-90.el7.centos.x86_64
    --> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-90.el7.centos.x86_64
    --> Running transaction check
    ---> Package httpd-tools.x86_64 0:2.4.6-90.el7.centos will be installed
    ---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ================================================================================
     Package            Arch          Version                     Repository   Size
    ================================================================================
    Installing:
     httpd              x86_64        2.4.6-90.el7.centos         base        2.7 M
    Installing for dependencies:
     httpd-tools        x86_64        2.4.6-90.el7.centos         base         91 k
     mailcap            noarch        2.1.41-2.el7                base         31 k
    
    Transaction Summary
    ================================================================================
    Install  1 Package (+2 Dependent packages)
    
    Total download size: 2.8 M
    Installed size: 9.6 M
    Downloading packages:
    --------------------------------------------------------------------------------
    Total                                              830 kB/s | 2.8 MB  00:03     
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : httpd-tools-2.4.6-90.el7.centos.x86_64                       1/3 
      Installing : mailcap-2.1.41-2.el7.noarch                                  2/3 
      Installing : httpd-2.4.6-90.el7.centos.x86_64                             3/3 
      Verifying  : mailcap-2.1.41-2.el7.noarch                                  1/3 
      Verifying  : httpd-tools-2.4.6-90.el7.centos.x86_64                       2/3 
      Verifying  : httpd-2.4.6-90.el7.centos.x86_64                             3/3 
    
    Installed:
      httpd.x86_64 0:2.4.6-90.el7.centos                                            
    
    Dependency Installed:
      httpd-tools.x86_64 0:2.4.6-90.el7.centos     mailcap.noarch 0:2.1.41-2.el7    
    
    Complete!
    "
        ]
    }

    9)service 模块

    该模块用于服务程序的管理。
      其主要选项如下:

    arguments #命令行提供额外的参数
    enabled #设置开机启动。
    name= #服务名称
    runlevel #开机启动的级别,一般不用指定。
    sleep #在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。(定义在剧本中。)
    state #有四种状态,分别为:started--->启动服务, stopped--->停止服务, restarted--->重启服务, reloaded--->重载配置

    ① 开启服务并设置自启动

    [root@localhost ~]# ansible webservers -m service -a 'name=httpd state=started enabled=true' 
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "enabled": true, 
        "name": "httpd", 
        "state": "started", 
        "status": {
            "ActiveEnterTimestampMonotonic": "0", 
            "ActiveExitTimestampMonotonic": "0", 
            "ActiveState": "inactive", 
            "After": "nss-lookup.target tmp.mount system.slice -.mount network.target basic.target systemd-journald.socket remote-fs.target", 
            "AllowIsolate": "no", 
            "AmbientCapabilities": "0", 
            "AssertResult": "no", 
            "AssertTimestampMonotonic": "0", 
            "Before": "shutdown.target", 
            "BlockIOAccounting": "no", 
            "BlockIOWeight": "18446744073709551615", 
            "CPUAccounting": "no", 
            "CPUQuotaPerSecUSec": "infinity", 
            "CPUSchedulingPolicy": "0", 
            "CPUSchedulingPriority": "0", 
            "CPUSchedulingResetOnFork": "no", 
            "CPUShares": "18446744073709551615", 
            "CanIsolate": "no", 
            "CanReload": "yes", 
            "CanStart": "yes", 
            "CanStop": "yes", 
            "CapabilityBoundingSet": "18446744073709551615", 
            "ConditionResult": "no", 
            "ConditionTimestampMonotonic": "0", 
            "Conflicts": "shutdown.target", 
            "ControlPID": "0", 
            "DefaultDependencies": "yes", 
            "Delegate": "no", 
            "Description": "The Apache HTTP Server", 
            "DevicePolicy": "auto", 
            "Documentation": "man:httpd(8) man:apachectl(8)", 
            "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
            "ExecMainCode": "0", 
            "ExecMainExitTimestampMonotonic": "0", 
            "ExecMainPID": "0", 
            "ExecMainStartTimestampMonotonic": "0", 
            "ExecMainStatus": "0", 
            "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
            "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
            "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
            "FailureAction": "none", 
            "FileDescriptorStoreMax": "0", 
            "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
            "GuessMainPID": "yes", 
            "IOScheduling": "0", 
            "Id": "httpd.service", 
            "IgnoreOnIsolate": "no", 
            "IgnoreOnSnapshot": "no", 
            "IgnoreSIGPIPE": "yes", 
            "InactiveEnterTimestampMonotonic": "0", 
            "InactiveExitTimestampMonotonic": "0", 
            "JobTimeoutAction": "none", 
            "JobTimeoutUSec": "0", 
            "KillMode": "control-group", 
            "KillSignal": "18", 
            "LimitAS": "18446744073709551615", 
            "LimitCORE": "18446744073709551615", 
            "LimitCPU": "18446744073709551615", 
            "LimitDATA": "18446744073709551615", 
            "LimitFSIZE": "18446744073709551615", 
            "LimitLOCKS": "18446744073709551615", 
            "LimitMEMLOCK": "65536", 
            "LimitMSGQUEUE": "819200", 
            "LimitNICE": "0", 
            "LimitNOFILE": "4096", 
            "LimitNPROC": "1802", 
            "LimitRSS": "18446744073709551615", 
            "LimitRTPRIO": "0", 
            "LimitRTTIME": "18446744073709551615", 
            "LimitSIGPENDING": "1802", 
            "LimitSTACK": "18446744073709551615", 
            "LoadState": "loaded", 
            "MainPID": "0", 
            "MemoryAccounting": "no", 
            "MemoryCurrent": "18446744073709551615", 
            "MemoryLimit": "18446744073709551615", 
            "MountFlags": "0", 
            "Names": "httpd.service", 
            "NeedDaemonReload": "no", 
            "Nice": "0", 
            "NoNewPrivileges": "no", 
            "NonBlocking": "no", 
            "NotifyAccess": "main", 
            "OOMScoreAdjust": "0", 
            "OnFailureJobMode": "replace", 
            "PermissionsStartOnly": "no", 
            "PrivateDevices": "no", 
            "PrivateNetwork": "no", 
            "PrivateTmp": "yes", 
            "ProtectHome": "no", 
            "ProtectSystem": "no", 
            "RefuseManualStart": "no", 
            "RefuseManualStop": "no", 
            "RemainAfterExit": "no", 
            "Requires": "-.mount basic.target", 
            "RequiresMountsFor": "/var/tmp", 
            "Restart": "no", 
            "RestartUSec": "100ms", 
            "Result": "success", 
            "RootDirectoryStartOnly": "no", 
            "RuntimeDirectoryMode": "0755", 
            "SameProcessGroup": "no", 
            "SecureBits": "0", 
            "SendSIGHUP": "no", 
            "SendSIGKILL": "yes", 
            "Slice": "system.slice", 
            "StandardError": "inherit", 
            "StandardInput": "null", 
            "StandardOutput": "journal", 
            "StartLimitAction": "none", 
            "StartLimitBurst": "5", 
            "StartLimitInterval": "10000000", 
            "StartupBlockIOWeight": "18446744073709551615", 
            "StartupCPUShares": "18446744073709551615", 
            "StatusErrno": "0", 
            "StopWhenUnneeded": "no", 
            "SubState": "dead", 
            "SyslogLevelPrefix": "yes", 
            "SyslogPriority": "30", 
            "SystemCallErrorNumber": "0", 
            "TTYReset": "no", 
            "TTYVHangup": "no", 
            "TTYVTDisallocate": "no", 
            "TasksAccounting": "no", 
            "TasksCurrent": "18446744073709551615", 
            "TasksMax": "18446744073709551615", 
            "TimeoutStartUSec": "1min 30s", 
            "TimeoutStopUSec": "1min 30s", 
            "TimerSlackNSec": "50000", 
            "Transient": "no", 
            "Type": "notify", 
            "UMask": "0022", 
            "UnitFilePreset": "disabled", 
            "UnitFileState": "disabled", 
            "Wants": "system.slice", 
            "WatchdogTimestampMonotonic": "0", 
            "WatchdogUSec": "0"
        }
    }
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "enabled": true, 
        "name": "httpd", 
        "state": "started", 
        "status": {
            "ActiveEnterTimestampMonotonic": "0", 
            "ActiveExitTimestampMonotonic": "0", 
            "ActiveState": "inactive", 
            "After": "nss-lookup.target tmp.mount system.slice basic.target remote-fs.target systemd-journald.socket -.mount network.target", 
            "AllowIsolate": "no", 
            "AmbientCapabilities": "0", 
            "AssertResult": "no", 
            "AssertTimestampMonotonic": "0", 
            "Before": "shutdown.target", 
            "BlockIOAccounting": "no", 
            "BlockIOWeight": "18446744073709551615", 
            "CPUAccounting": "no", 
            "CPUQuotaPerSecUSec": "infinity", 
            "CPUSchedulingPolicy": "0", 
            "CPUSchedulingPriority": "0", 
            "CPUSchedulingResetOnFork": "no", 
            "CPUShares": "18446744073709551615", 
            "CanIsolate": "no", 
            "CanReload": "yes", 
            "CanStart": "yes", 
            "CanStop": "yes", 
            "CapabilityBoundingSet": "18446744073709551615", 
            "ConditionResult": "no", 
            "ConditionTimestampMonotonic": "0", 
            "Conflicts": "shutdown.target", 
            "ControlPID": "0", 
            "DefaultDependencies": "yes", 
            "Delegate": "no", 
            "Description": "The Apache HTTP Server", 
            "DevicePolicy": "auto", 
            "Documentation": "man:httpd(8) man:apachectl(8)", 
            "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
            "ExecMainCode": "0", 
            "ExecMainExitTimestampMonotonic": "0", 
            "ExecMainPID": "0", 
            "ExecMainStartTimestampMonotonic": "0", 
            "ExecMainStatus": "0", 
            "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
            "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
            "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
            "FailureAction": "none", 
            "FileDescriptorStoreMax": "0", 
            "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
            "GuessMainPID": "yes", 
            "IOScheduling": "0", 
            "Id": "httpd.service", 
            "IgnoreOnIsolate": "no", 
            "IgnoreOnSnapshot": "no", 
            "IgnoreSIGPIPE": "yes", 
            "InactiveEnterTimestampMonotonic": "0", 
            "InactiveExitTimestampMonotonic": "0", 
            "JobTimeoutAction": "none", 
            "JobTimeoutUSec": "0", 
            "KillMode": "control-group", 
            "KillSignal": "18", 
            "LimitAS": "18446744073709551615", 
            "LimitCORE": "18446744073709551615", 
            "LimitCPU": "18446744073709551615", 
            "LimitDATA": "18446744073709551615", 
            "LimitFSIZE": "18446744073709551615", 
            "LimitLOCKS": "18446744073709551615", 
            "LimitMEMLOCK": "65536", 
            "LimitMSGQUEUE": "819200", 
            "LimitNICE": "0", 
            "LimitNOFILE": "4096", 
            "LimitNPROC": "1802", 
            "LimitRSS": "18446744073709551615", 
            "LimitRTPRIO": "0", 
            "LimitRTTIME": "18446744073709551615", 
            "LimitSIGPENDING": "1802", 
            "LimitSTACK": "18446744073709551615", 
            "LoadState": "loaded", 
            "MainPID": "0", 
            "MemoryAccounting": "no", 
            "MemoryCurrent": "18446744073709551615", 
            "MemoryLimit": "18446744073709551615", 
            "MountFlags": "0", 
            "Names": "httpd.service", 
            "NeedDaemonReload": "no", 
            "Nice": "0", 
            "NoNewPrivileges": "no", 
            "NonBlocking": "no", 
            "NotifyAccess": "main", 
            "OOMScoreAdjust": "0", 
            "OnFailureJobMode": "replace", 
            "PermissionsStartOnly": "no", 
            "PrivateDevices": "no", 
            "PrivateNetwork": "no", 
            "PrivateTmp": "yes", 
            "ProtectHome": "no", 
            "ProtectSystem": "no", 
            "RefuseManualStart": "no", 
            "RefuseManualStop": "no", 
            "RemainAfterExit": "no", 
            "Requires": "basic.target -.mount", 
            "RequiresMountsFor": "/var/tmp", 
            "Restart": "no", 
            "RestartUSec": "100ms", 
            "Result": "success", 
            "RootDirectoryStartOnly": "no", 
            "RuntimeDirectoryMode": "0755", 
            "SameProcessGroup": "no", 
            "SecureBits": "0", 
            "SendSIGHUP": "no", 
            "SendSIGKILL": "yes", 
            "Slice": "system.slice", 
            "StandardError": "inherit", 
            "StandardInput": "null", 
            "StandardOutput": "journal", 
            "StartLimitAction": "none", 
            "StartLimitBurst": "5", 
            "StartLimitInterval": "10000000", 
            "StartupBlockIOWeight": "18446744073709551615", 
            "StartupCPUShares": "18446744073709551615", 
            "StatusErrno": "0", 
            "StopWhenUnneeded": "no", 
            "SubState": "dead", 
            "SyslogLevelPrefix": "yes", 
            "SyslogPriority": "30", 
            "SystemCallErrorNumber": "0", 
            "TTYReset": "no", 
            "TTYVHangup": "no", 
            "TTYVTDisallocate": "no", 
            "TasksAccounting": "no", 
            "TasksCurrent": "18446744073709551615", 
            "TasksMax": "18446744073709551615", 
            "TimeoutStartUSec": "1min 30s", 
            "TimeoutStopUSec": "1min 30s", 
            "TimerSlackNSec": "50000", 
            "Transient": "no", 
            "Type": "notify", 
            "UMask": "0022", 
            "UnitFilePreset": "disabled", 
            "UnitFileState": "disabled", 
            "Wants": "system.slice", 
            "WatchdogTimestampMonotonic": "0", 
            "WatchdogUSec": "0"
        }
    }

    我们可以去查看一下端口是否打开:

    [root@localhost ~]# ansible webservers -m shell -a 'ss -ntl'
    192.168.1.221 | CHANGED | rc=0 >>
    State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
    LISTEN     0      128          *:22                       *:*                  
    LISTEN     0      100    127.0.0.1:25                       *:*                  
    LISTEN     0      128         :::80                      :::*                  
    LISTEN     0      128         :::22                      :::*                  
    LISTEN     0      100        ::1:25                      :::*                  
    192.168.1.223 | CHANGED | rc=0 >>
    State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
    LISTEN     0      128          *:22                       *:*                  
    LISTEN     0      100    127.0.0.1:25                       *:*                  
    LISTEN     0      128         :::80                      :::*                  
    LISTEN     0      128         :::22                      :::*                  
    LISTEN     0      100        ::1:25                      :::*                  
    LISTEN     0      80          :::3306                    :::*     

    可以看出我们的80端口已经打开。

    ② 关闭服务
      我们也可以通过该模块来关闭我们的服务:

    [root@localhost ~]# ansible webservers -m service -a 'name=httpd state=stopped'
    [root@localhost ~]# ansible webservers -m shell -a 'ss -ntl'
    192.168.1.221 | CHANGED | rc=0 >>
    State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
    LISTEN     0      128          *:22                       *:*                  
    LISTEN     0      100    127.0.0.1:25                       *:*                  
    LISTEN     0      128         :::22                      :::*                  
    LISTEN     0      100        ::1:25                      :::*                  
    192.168.1.223 | CHANGED | rc=0 >>
    State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
    LISTEN     0      128          *:22                       *:*                  
    LISTEN     0      100    127.0.0.1:25                       *:*                  
    LISTEN     0      128         :::22                      :::*                  
    LISTEN     0      100        ::1:25                      :::*                  
    LISTEN     0      80          :::3306                    :::*   

    可以看出,我们已经没有80端口了,说明我们的httpd服务已经关闭了。

    10)user 模块

      该模块主要是用来管理用户账号。
      其主要选项如下:

    comment  # 用户的描述信息
    createhome  # 是否创建家目录
    force  # 在使用state=absent时, 行为与userdel –force一致.
    group  # 指定基本组
    groups  # 指定附加组,如果指定为(groups=)表示删除所有组
    home  # 指定用户家目录
    move_home  # 如果设置为home=时, 试图将用户主目录移动到指定的目录
    name  # 指定用户名
    non_unique  # 该选项允许改变非唯一的用户ID值
    password  # 指定用户密码
    remove  # 在使用state=absent时, 行为是与userdel –remove一致
    shell  # 指定默认shell
    state  # 设置帐号状态,不指定为创建,指定值为absent表示删除
    system  # 当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户
    uid  # 指定用户的uid

    ① 添加一个用户并指定其 uid

    [root@localhost ~]# ansible webservers -m user -a 'name=keer uid=11111'
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "comment": "", 
        "create_home": true, 
        "group": 11111, 
        "home": "/home/keer", 
        "name": "keer", 
        "shell": "/bin/bash", 
        "state": "present", 
        "system": false, 
        "uid": 11111
    }
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "comment": "", 
        "create_home": true, 
        "group": 11111, 
        "home": "/home/keer", 
        "name": "keer", 
        "shell": "/bin/bash", 
        "state": "present", 
        "system": false, 
        "uid": 11111
    }
    [root@localhost ~]# ansible webservers -m shell -a 'cat /etc/passwd |grep keer'
    192.168.1.221 | CHANGED | rc=0 >>
    keer:x:11111:11111::/home/keer:/bin/bash
    192.168.1.223 | CHANGED | rc=0 >>
    keer:x:11111:11111::/home/keer:/bin/bash

    ② 删除用户

    [root@localhost ~]# ansible webservers -m user -a 'name=keer state=absent'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "force": false, 
        "name": "keer", 
        "remove": false, 
        "state": "absent"
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "force": false, 
        "name": "keer", 
        "remove": false, 
        "state": "absent"
    }
    [root@localhost ~]# ansible webservers -m shell -a 'cat /etc/passwd |grep keer'
    192.168.1.221 | FAILED | rc=1 >>
    non-zero return code
    192.168.1.223 | FAILED | rc=1 >>
    non-zero return code

    11)group 模块

    该模块主要用于添加或删除组。
      常用的选项如下:

    gid=  #设置组的GID号
    name=  #指定组的名称
    state=  #指定组的状态,默认为创建,设置值为absent为删除
    system=  #设置值为yes,表示创建为系统组
    [root@localhost ~]# ansible webservers -m group -a 'name=sanguo gid=12222'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "gid": 12222, 
        "name": "sanguo", 
        "state": "present", 
        "system": false
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "gid": 12222, 
        "name": "sanguo", 
        "state": "present", 
        "system": false
    }
    [root@localhost ~]# ansible webservers -m shell -a 'cat /etc/group | grep 12222' 
    192.168.1.221 | CHANGED | rc=0 >>
    sanguo:x:12222:
    192.168.1.223 | CHANGED | rc=0 >>
    sanguo:x:12222:

    ② 删除组

    [root@localhost ~]# ansible webservers -m group -a 'name=sanguo state=absent'
    192.168.1.221 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "name": "sanguo", 
        "state": "absent"
    }
    192.168.1.223 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "name": "sanguo", 
        "state": "absent"
    }
    [root@localhost ~]# ansible webservers -m shell -a 'cat /etc/group | grep 12222' 
    192.168.1.221 | FAILED | rc=1 >>
    non-zero return code
    192.168.1.223 | FAILED | rc=1 >>
    non-zero return code

    12)script 模块

      该模块用于将本机的脚本在被管理端的机器上运行。
      该模块直接指定脚本的路径即可,我们通过例子来看一看到底如何使用的:
      首先,我们写一个脚本,并给其加上执行权限:

    [root@localhost ~]# vim /tmp/df.sh
    
    #!/bin/bash
    
        date >> /tmp/disk_total.log
        df -lh >> /tmp/disk_total.log
    ~
    [root@localhost tmp]# chmod a+x df.sh 
    [root@localhost tmp]# 
    [root@localhost tmp]# ansible webservers -m script -a '/tmp/df.sh'
    192.168.1.223 | CHANGED => {
        "changed": true, 
        "rc": 0, 
        "stderr": "Shared connection to 192.168.1.223 closed.
    ", 
        "stderr_lines": [
            "Shared connection to 192.168.1.223 closed."
        ], 
        "stdout": "", 
        "stdout_lines": []
    }
    192.168.1.221 | CHANGED => {
        "changed": true, 
        "rc": 0, 
        "stderr": "Shared connection to 192.168.1.221 closed.
    ", 
        "stderr_lines": [
            "Shared connection to 192.168.1.221 closed."
        ], 
        "stdout": "", 
        "stdout_lines": []
    }
    [root@localhost tmp]# ansible webservers -m shell -a 'cat /tmp/disk_total.log'
    192.168.1.223 | CHANGED | rc=0 >>
    2020年 01月 17日 星期五 14:49:06 CST
    文件系统                 容量  已用  可用 已用% 挂载点
    /dev/mapper/centos-root   19G  3.1G   16G   17% /
    devtmpfs                 226M     0  226M    0% /dev
    tmpfs                    237M     0  237M    0% /dev/shm
    tmpfs                    237M   13M  224M    6% /run
    tmpfs                    237M     0  237M    0% /sys/fs/cgroup
    /dev/sda1                297M  108M  189M   37% /boot
    tmpfs                     48M     0   48M    0% /run/user/0
    192.168.1.221 | CHANGED | rc=0 >>
    2020年 01月 17日 星期五 14:49:06 CST
    文件系统                 容量  已用  可用 已用% 挂载点
    /dev/mapper/centos-root   19G  1.6G   18G    9% /
    devtmpfs                 226M     0  226M    0% /dev
    tmpfs                    237M     0  237M    0% /dev/shm
    tmpfs                    237M  8.7M  228M    4% /run
    tmpfs                    237M     0  237M    0% /sys/fs/cgroup
    /dev/sda1                297M  108M  190M   37% /boot
    tmpfs                     48M     0   48M    0% /run/user/0

    13)setup 模块

      该模块主要用于收集信息,是通过调用facts组件来实现的。
      facts组件是Ansible用于采集被管机器设备信息的一个功能,我们可以使用setup模块查机器的所有facts信息,可以使用filter来查看指定信息。整个facts信息被包装在一个JSON格式的数据结构中,ansible_facts是最上层的值。
      facts就是变量,内建变量 。每个主机的各种信息,cpu颗数、内存大小等。会存在facts中的某个变量中。调用后返回很多对应主机的信息,在后面的操作中可以根据不同的信息来做不同的操作。如redhat系列用yum安装,而debian系列用apt来安装软件。
    ① 查看信息
      我们可以直接用命令获取到变量的值,具体我们来看看例子

    [root@localhost tmp]# ansible webservers -m setup -a 'filter="*mem*"'
    192.168.1.221 | SUCCESS => {
        "ansible_facts": {
            "ansible_memfree_mb": 73, 
            "ansible_memory_mb": {
                "nocache": {
                    "free": 241, 
                    "used": 231
                }, 
                "real": {
                    "free": 73, 
                    "total": 472, 
                    "used": 399
                }, 
                "swap": {
                    "cached": 0, 
                    "free": 999, 
                    "total": 999, 
                    "used": 0
                }
            }, 
            "ansible_memtotal_mb": 472, 
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false
    }
    192.168.1.223 | SUCCESS => {
        "ansible_facts": {
            "ansible_memfree_mb": 34, 
            "ansible_memory_mb": {
                "nocache": {
                    "free": 169, 
                    "used": 303
                }, 
                "real": {
                    "free": 34, 
                    "total": 472, 
                    "used": 438
                }, 
                "swap": {
                    "cached": 3, 
                    "free": 951, 
                    "total": 999, 
                    "used": 48
                }
            }, 
            "ansible_memtotal_mb": 472, 
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false

    我们可以通过命令查看一下内存的大小以确认一下是否一致:

    [root@localhost tmp]# ansible webservers -m shell -a 'free -m'
    192.168.1.223 | CHANGED | rc=0 >>
                  total        used        free      shared  buff/cache   available
    Mem:            472         255          32          10         184         167
    Swap:           999          48         951
    192.168.1.221 | CHANGED | rc=0 >>
                  total        used        free      shared  buff/cache   available
    Mem:            472         148          72           8         252         253
    Swap:           999           0         999

    ② 保存信息
      我们的setup模块还有一个很好用的功能就是可以保存我们所筛选的信息至我们的主机上,同时,文件名为我们被管制的主机的IP,这样方便我们知道是哪台机器出的问题。
      我们可以看一看例子:

    [root@localhost tmp]# ansible webservers -m setup -a 'filter="*mem*"' --tree /tmp/facts
    192.168.1.221 | SUCCESS => {
        "ansible_facts": {
            "ansible_memfree_mb": 68, 
            "ansible_memory_mb": {
                "nocache": {
                    "free": 241, 
                    "used": 231
                }, 
                "real": {
                    "free": 68, 
                    "total": 472, 
                    "used": 404
                }, 
                "swap": {
                    "cached": 0, 
                    "free": 999, 
                    "total": 999, 
                    "used": 0
                }
            }, 
            "ansible_memtotal_mb": 472, 
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false
    }
    192.168.1.223 | SUCCESS => {
        "ansible_facts": {
            "ansible_memfree_mb": 29, 
            "ansible_memory_mb": {
                "nocache": {
                    "free": 169, 
                    "used": 303
                }, 
                "real": {
                    "free": 29, 
                    "total": 472, 
                    "used": 443
                }, 
                "swap": {
                    "cached": 3, 
                    "free": 951, 
                    "total": 999, 
                    "used": 48
                }
            }, 
            "ansible_memtotal_mb": 472, 
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": false
    }
    [root@localhost tmp]# cd /tmp/facts/
    [root@localhost facts]# ls
    192.168.1.221  192.168.1.223
    [root@localhost facts]# ls 192.168.1.221 -l
    -rw-r--r--. 1 root root 315 1月  17 14:54 192.168.1.221
    [root@localhost facts]# ls 192.168.1.223 -l
    -rw-r--r--. 1 root root 316 1月  17 14:54 192.168.1.223
    
    [root@localhost facts]# cat 192.168.1.221
    {"ansible_facts": {"ansible_memfree_mb": 68, "ansible_memory_mb": {"nocache": {"free": 241, "used": 231}, "real": {"free": 68, "total": 472, "used": 404}, "swap": {"cached": 0, "free": 999, "total": 999, "used": 0}}, "ansible_memtotal_mb": 472, "discovered_interpreter_python": "/usr/bin/python"}, "changed": false}[root@localhost facts]# cat 192.168.1.223
    {"ansible_facts": {"ansible_memfree_mb": 29, "ansible_memory_mb": {"nocache": {"free": 169, "used": 303}, "real": {"free": 29, "total": 472, "used": 443}, "swap": {"cached": 3, "free": 951, "total": 999, "used": 48}}, "ansible_memtotal_mb": 472, "discovered_interpreter_python": "/usr/bin/python"}, "changed": false}[root@localhost facts]# 

    顾名思义,该模块主要用于软件的安装。
      其选项如下:

    name=

  • 相关阅读:
    20155229-付钰涵-分析自我技能延展到c语言学习状况
    预备作业①
    读《嵌入式系统项目分析入门与实践》⑤
    读《嵌入式系统项目分析入门与实践》④
    读《嵌入式系统项目分析入门与实践》③
    读《嵌入式系统项目分析入门与实践》②
    读《嵌入式系统项目分析入门与实践》①
    读《大学有感》④
    读《大学之路》有感③
    读《大学之路》有感②
  • 原文地址:https://www.cnblogs.com/liujunjun/p/12204954.html
Copyright © 2020-2023  润新知