zoukankan      html  css  js  c++  java
  • ansible-常用模块

    1. ansible-常用模块
        根据官方的分类,将模块按功能分类为:云模块、命令模块、数据库模块、文件模块、资产模块、消息模块、监控模块、网络模块、通知模块、包管理模块、源码控制模块、系统模块、单元模块、web设施模块、windows模块

    • user:配置用户
    • group:配置用户组
    • cron:配置计划任务
    • copy:复制文件到远程主机
    • file: 用于配置文件属性
    • yum:用于安装软件包
    • service:用于管理服务
    • shell: 用于执行命令可以带 “ |”管道符号等
    • scripts:在远程主机执行控制端的脚本文件
    • setup:查看远程主机的基本信息
    • filesystem:在块设备上创建文件系统
    • mount:配置挂载点
    • synchronize:使用rsync同步文件
    • get_url:该模块主要用于从http、ftp、https服务器上下载文件(类似于wget)
    • package:使用os包管理器安装,升级和删除包
    • stat:获取远程主机文件状态信息。
    • unarchive: 用于解压文件
    • command:在远程主机上执行命令
    • raw:类似于shell模块,支持管道
    • ping:用于检测远程主机是否存活

    2.模块的使用

     查看模块帮助

    1 [root@test-1 bin]# ansible-doc -l                            #查看所有模块
    2 [root@test-1 bin]#ansible-doc -s MODULE_NAME           #查看指定模块的详细帮助

    3.ansible命令应用基础

       使用语法:

    1 ansible <host-pattern> [-f forks] [-m module_name] [-a args]

       注释:

    • -f   forks:启动的并发线程数
    • -m module_name:  要使用的模块
    • -a  args:模块特有的参数

    4.模块使用案例

     4.1 ping模块

        测试主机是否通的,用法很简单,如果成功就返回的是pong。

     1 [root@test-1 ansible]# ansible test -m ping
     2 [DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of Ansible Become, which is a generic framework. See become_user. , use become instead. This feature will be 
     3 removed in version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
     4 192.168.3.174 | SUCCESS => {
     5     "changed": false, 
     6     "ping": "pong"
     7 }
     8 192.168.3.175 | SUCCESS => {
     9     "changed": false, 
    10     "ping": "pong"
    11 }

     4.2 file-模块
           file模块主要用于远程主机上的文件操作,file模块包含如下选项:

     1 force:需要在两种情况下强制创建软连接。
     2    • 一种是源文件不存在但之后会创建的情况下;
     3    • 另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no 
     4 group:定义文件/目录的属组
     5 owner:定义文件/目录的属主
     6 mode:定义文件/目录的权限
     7 path:必选项,定义文件/目录的路径
     8 recurse:递归设置文件的属性,只对目录有效
     9 src:要被链接的源文件的路径,只应用于state=link的情况
    10 dest:被链接到的路径,只应用于state=link的情况 
    11 state:定义文件状态
    12    • directory:如果目录不存在,创建目录
    13    • file:即使文件不存在,也不会被创建
    14    • link:创建软链接
    15    • hard:创建硬链接
    16    • touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
    17    • absent:删除目录、文件或者取消链接文件

      4.2.1 案例1-用file创建一个软连接/etc/fstab到/tmp/fstab

     1     [root@test-1 ansible]# ansible test -m file -a "src=/etc/fstab dest=/tmp/fstab  state=link"
     2     [DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of Ansible Become, which is a generic framework. See become_user. , use become instead. This feature will be 
     3     removed in version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
     4     192.168.3.175 | CHANGED => {
     5         "changed": true, 
     6         "dest": "/tmp/fstab", 
     7         "gid": 0, 
     8         "group": "root", 
     9         "mode": "0777", 
    10         "owner": "root", 
    11         "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    12         "size": 10, 
    13         "src": "/etc/fstab", 
    14         "state": "link", 
    15         "uid": 0
    16     }
    17     192.168.3.174 | CHANGED => {
    18         "changed": true, 
    19         "dest": "/tmp/fstab", 
    20         "gid": 0, 
    21         "group": "root", 
    22         "mode": "0777", 
    23         "owner": "root", 
    24         "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    25         "size": 10, 
    26         "src": "/etc/fstab", 
    27         "state": "link", 
    28         "uid": 0
    29     }

        执行结果:

    1     [root@test-2 tmp]# ll 
    2     total 8
    3     lrwxrwxrwx. 1 root root  10 Nov 19 02:44 fstab -> /etc/fstab
    4     -rwx------. 1 root root 836 Oct 24 09:40 ks-script-6aY4Ug
    5     drwx------. 3 root root  17 Oct 25 23:39 systemd-private-664f2393bb954d4d812ce589bd921c84-chronyd.service-sclu10
    6     -rw-r--r--. 1 root root   8 Oct 25 22:26 test.txt
    7     drwx------. 2 root root   6 Oct 24 09:44 vmware-root
    8     -rw-------. 1 root root   0 Oct 24 09:36 yum.log

      4.2.2  案例2-我们需要在远程服务器上/tmp/下创建一个file文件

     1 [root@test-1 ansible]# ansible test -m file -a 'path=/tmp/file state=touch'
     2 [DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of Ansible Become, which is a generic framework. See become_user. , use become instead. This feature will be 
     3 removed in version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
     4 192.168.3.174 | CHANGED => {
     5     "changed": true, 
     6     "dest": "/tmp/file", 
     7     "gid": 0, 
     8     "group": "root", 
     9     "mode": "0644", 
    10     "owner": "root", 
    11     "secontext": "unconfined_u:object_r:user_tmp_t:s0", 
    12     "size": 0, 
    13     "state": "file", 
    14     "uid": 0

        执行结果:

    1 [root@test-2 tmp]# ll
    2 total 8
    3 -rw-r--r--. 1 root root   0 Nov 19 03:12 file
    4 lrwxrwxrwx. 1 root root  10 Nov 19 02:44 fstab -> /etc/fstab
    5 -rwx------. 1 root root 836 Oct 24 09:40 ks-script-6aY4Ug
    6 drwx------. 3 root root  17 Oct 25 23:39 systemd-private-664f2393bb954d4d812ce589bd921c84-chronyd.service-sclu10
    7 -rw-r--r--. 1 root root   8 Oct 25 22:26 test.txt
    8 drwx------. 2 root root   6 Oct 24 09:44 vmware-root
    9 -rw-------. 1 root root   0 Oct 24 09:36 yum.log

      4.3 copy模块

    1 backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no 
    2 content:用于替代"src",可以直接设定指定文件的值 
    3 dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录 
    4 directory_mode:递归的设定目录的权限,默认为系统默认权限
    5 force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
    6 others:所有的file模块里的选项都可以在这里使用
    7 src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用"/"来结尾,则只复制目录里的内容,如果没有使用"/"来结尾,则包含目录在内的整个内容全部复制,类似于rsync。 
    8 validate :The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the visudo example below.

      4.3.1 案例1-从本地拷贝文件到ansibel目标的目录

     1 [root@test-1 ansible]# touch /tmp/aa                                   #本地测试创建的aa文件
     2 [root@test-1 ansible]# ansible test -m copy -a "src=/tmp/aa dest=/tmp/aa"           
     3 [DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of Ansible Become, which is a generic framework. See become_user. , use become instead. This feature will be 
     4 removed in version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
     5 192.168.3.174 | CHANGED => {
     6     "changed": true, 
     7     "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
     8     "dest": "/tmp/aa", 
     9     "gid": 0, 
    10     "group": "root", 
    11     "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    12     "mode": "0644", 
    13     "owner": "root", 
    14     "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    15     "size": 0, 
    16     "src": "/root/.ansible/tmp/ansible-tmp-1542616228.03-86258002572076/source", 
    17     "state": "file", 
    18     "uid": 0
    19 }

        执行结果:

     1 [root@test-2 tmp]# ll
     2 total 8
     3 -rw-r--r--. 1 root root   0 Nov 19 03:30 aa
     4 -rwxr-xr-x. 1 root root   0 Nov 19 03:12 file
     5 lrwxrwxrwx. 1 root root  10 Nov 19 02:44 fstab -> /etc/fstab
     6 -rwx------. 1 root root 836 Oct 24 09:40 ks-script-6aY4Ug
     7 drwx------. 3 root root  17 Oct 25 23:39 systemd-private-664f2393bb954d4d812ce589bd921c84-chronyd.service-sclu10
     8 -rw-r--r--. 1 root root   8 Oct 25 22:26 test.txt
     9 drwx------. 2 root root   6 Oct 24 09:44 vmware-root
    10 -rw-------. 1 root root   0 Oct 24 09:36 yum.log

       4.3.2 案例2-ansible使用backup进行备份

     1 [root@test-1 ansible]# vim /tmp/aa 
     2 [root@test-1 ansible]# ansible test -m copy -a "src=/tmp/aa dest=/tmp/aa backup=yes"
     3 [DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of Ansible Become, which is a generic framework. See become_user. , use become instead. This feature will be 
     4 removed in version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
     5 192.168.3.174 | CHANGED => {
     6     "backup_file": "/tmp/aa.3042.2018-11-19@03:37:06~", 
     7     "changed": true, 
     8     "checksum": "5730dd3a58d64a39a7fc704c3c5570d70303d9db", 
     9     "dest": "/tmp/aa", 
    10     "gid": 0, 
    11     "group": "root", 
    12     "md5sum": "96fdb0b7ddbb489f8636769965584623", 
    13     "mode": "0644", 
    14     "owner": "root", 
    15     "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    16     "size": 35, 
    17     "src": "/root/.ansible/tmp/ansible-tmp-1542616624.56-136259009428901/source", 
    18     "state": "file", 
    19     "uid": 0

       执行结果:

     1 [root@test-2 tmp]# ll
     2 total 16
     3 -rw-r--r--. 1 root root  35 Nov 19 03:37 aa
     4 -rw-r--r--. 1 root root  56 Nov 19 03:36 aa.3042.2018-11-19@03:37:06~           #这里是ansible使用的
     5 -rwxr-xr-x. 1 root root   0 Nov 19 03:12 file
     6 lrwxrwxrwx. 1 root root  10 Nov 19 02:44 fstab -> /etc/fstab
     7 -rwx------. 1 root root 836 Oct 24 09:40 ks-script-6aY4Ug
     8 drwx------. 3 root root  17 Oct 25 23:39 systemd-private-664f2393bb954d4d812ce589bd921c84-chronyd.service-sclu10
     9 -rw-r--r--. 1 root root   8 Oct 25 22:26 test.txt
    10 drwx------. 2 root root   6 Oct 24 09:44 vmware-root
    11 -rw-------. 1 root root   0 Oct 24 09:36 yum.log

    4.4 command-模块

          在远程主机上执行命令

          command模块包含如下选项:

    1 creates:一个文件名,当该文件存在,则该命令不执行
    2 free_form:要执行的linux指令
    3 chdir:在执行指令之前,先切换到该指定的目录
    4 removes:一个文件名,当该文件不存在,则该选项不执行
    5 executable:切换shell来执行指令,该执行路径必须是一个绝对路径

      4.4.1 案例1-creates文件存在,不执行后面的命令 

     1 [root@test-1 ansible]# ansible test  -a 'creates=/tmp/file ls /root'
     2 [DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of Ansible Become, which is a generic framework. See become_user. , use become instead. This feature will be 
     3 removed in version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
     4 192.168.3.174 | SUCCESS | rc=0 >>
     5 skipped, since /tmp/file exists
     6 
     7 [root@test-1 ansible]# ansible test  -a 'creates=/tmp/file2 ls /root'
     8 [DEPRECATION WARNING]: DEFAULT_SUDO_USER option, In favor of Ansible Become, which is a generic framework. See become_user. , use become instead. This feature will be 
     9 removed in version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
    10 192.168.3.174 | CHANGED | rc=0 >>
    11 anaconda-ks.cfg

       执行结果:

    1 [root@test-2 tmp]# ll /root/
    2 total 4
    3 -rw-------. 1 root root 1340 Oct 24 09:40 anaconda-ks.cfg

      4.4.2 案例2-chdir在执行指令前,先切到指定目录,然后在做后面命令操作

    1 [root@test-1 ansible]# ansible test -m command -a 'chdir=/tmp tar zcf aa.tar.gz aa'
    2 192.168.3.174 | CHANGED | rc=0 >>

        执行结果:

     1 [root@test-2 tmp]# ll
     2 total 20
     3 -rw-r--r--. 1 root root  35 Nov 19 03:37 aa
     4 -rw-r--r--. 1 root root  56 Nov 19 03:36 aa.3042.2018-11-19@03:37:06~
     5 -rw-r--r--. 1 root root 137 Nov 19 04:37 aa.tar.gz
     6 -rwxr-xr-x. 1 root root   0 Nov 19 03:12 file
     7 lrwxrwxrwx. 1 root root  10 Nov 19 02:44 fstab -> /etc/fstab
     8 -rwx------. 1 root root 836 Oct 24 09:40 ks-script-6aY4Ug
     9 drwx------. 3 root root  17 Oct 25 23:39 systemd-private-664f2393bb954d4d812ce589bd921c84-chronyd.service-sclu10
    10 -rw-r--r--. 1 root root   8 Oct 25 22:26 test.txt
    11 drwx------. 2 root root   6 Oct 24 09:44 vmware-root
    12 -rw-------. 1 root root   0 Oct 24 09:36 yum.log

     4.5 shell模块

           功能:执行的命令中有管道或者变量,就需要使用shell

     1 [root@test-1 ansible]# ansible-doc -s shell
     2 - name: Execute commands in nodes.
     3   shell:
     4       chdir:                 # 执行之前,先cd到指定目录在执行命令
     5       creates:               # 一个文件名,当这个文件存在,则该命令不执行
     6       executable:            # 切换shell来执行命令,需要使用命令的绝对路径
     7       free_form:             # (required) The shell module takes a free form command to run, as a string.  There's not an actual option named "free form".  See the
     8                                examples!
     9       removes:               # a filename, when it does not exist, this step will *not* be run.
    10       stdin:                 # Set the stdin of the command directly to the specified value.
    11       warn:                  # if command warnings are on in ansible.cfg, do not warn about this particular line if set to no/false.

      4.5.1 案例1-shell模块可以支持|  等

    1 [root@test-1 ansible]# ansible test -m shell -a 'netstat -lntup |grep 22'
    2 192.168.3.174 | CHANGED | rc=0 >>
    3 tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      975/sshd            
    4 tcp6       0      0 :::22                   :::*                    LISTEN      975/sshd   

    4.6 service模块

          用于管理服务
          该模块包含如下选项

    1 arguments:给命令行提供一些选项 
    2 enabled:是否开机启动 yes|no
    3 name:必选项,服务名称 
    4 pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行
    5 runlevel:运行级别
    6 sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟
    7 state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)

      4.6.1 service设置开机启动

      1 [root@test-1 bin]# ansible web1 -m service -a "name=nginx  enabled=yes"
      2 192.168.200.133 | CHANGED => {
      3     "ansible_facts": {
      4         "discovered_interpreter_python": "/usr/bin/python"
      5     }, 
      6     "changed": true, 
      7     "enabled": true, 
      8     "name": "nginx", 
      9     "status": {
     10         "ActiveEnterTimestamp": "Thu 2019-08-22 11:22:08 CST", 
     11         "ActiveEnterTimestampMonotonic": "644109632234", 
     12         "ActiveExitTimestamp": "Thu 2019-08-22 11:22:08 CST", 
     13         "ActiveExitTimestampMonotonic": "644109612635", 
     14         "ActiveState": "active", 
     15         "After": "systemd-journald.socket remote-fs.target basic.target network-online.target nss-lookup.target system.slice", 
     16         "AllowIsolate": "no", 
     17         "AmbientCapabilities": "0", 
     18         "AssertResult": "yes", 
     19         "AssertTimestamp": "Thu 2019-08-22 11:22:08 CST", 
     20         "AssertTimestampMonotonic": "644109623574", 
     21         "Before": "shutdown.target", 
     22         "BlockIOAccounting": "no", 
     23         "BlockIOWeight": "18446744073709551615", 
     24         "CPUAccounting": "no", 
     25         "CPUQuotaPerSecUSec": "infinity", 
     26         "CPUSchedulingPolicy": "0", 
     27         "CPUSchedulingPriority": "0", 
     28         "CPUSchedulingResetOnFork": "no", 
     29         "CPUShares": "18446744073709551615", 
     30         "CanIsolate": "no", 
     31         "CanReload": "yes", 
     32         "CanStart": "yes", 
     33         "CanStop": "yes", 
     34         "CapabilityBoundingSet": "18446744073709551615", 
     35         "ConditionResult": "yes", 
     36         "ConditionTimestamp": "Thu 2019-08-22 11:22:08 CST", 
     37         "ConditionTimestampMonotonic": "644109623574", 
     38         "Conflicts": "shutdown.target", 
     39         "ControlGroup": "/system.slice/nginx.service", 
     40         "ControlPID": "0", 
     41         "DefaultDependencies": "yes", 
     42         "Delegate": "no", 
     43         "Description": "nginx - high performance web server", 
     44         "DevicePolicy": "auto", 
     45         "Documentation": "http://nginx.org/en/docs/", 
     46         "ExecMainCode": "0", 
     47         "ExecMainExitTimestampMonotonic": "0", 
     48         "ExecMainPID": "20717", 
     49         "ExecMainStartTimestamp": "Thu 2019-08-22 11:22:08 CST", 
     50         "ExecMainStartTimestampMonotonic": "644109632178", 
     51         "ExecMainStatus": "0", 
     52         "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -s HUP $MAINPID ; ignore_errors=no ; start_time=[Tue 2019-08-20 20:41:12 CST] ; stop_time=[Tue 2019-08-20 20:41:12 CST] ; pid=18612 ; code=exited ; status=0 }", 
     53         "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -c /etc/nginx/nginx.conf ; ignore_errors=no ; start_time=[Thu 2019-08-22 11:22:08 CST] ; stop_time=[Thu 2019-08-22 11:22:08 CST] ; pid=20716 ; code=exited ; status=0 }", 
     54         "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -s TERM $MAINPID ; ignore_errors=no ; start_time=[Thu 2019-08-22 11:22:08 CST] ; stop_time=[Thu 2019-08-22 11:22:08 CST] ; pid=20713 ; code=exited ; status=0 }", 
     55         "FailureAction": "none", 
     56         "FileDescriptorStoreMax": "0", 
     57         "FragmentPath": "/usr/lib/systemd/system/nginx.service", 
     58         "GuessMainPID": "yes", 
     59         "IOScheduling": "0", 
     60         "Id": "nginx.service", 
     61         "IgnoreOnIsolate": "no", 
     62         "IgnoreOnSnapshot": "no", 
     63         "IgnoreSIGPIPE": "yes", 
     64         "InactiveEnterTimestamp": "Thu 2019-08-22 11:22:08 CST", 
     65         "InactiveEnterTimestampMonotonic": "644109623218", 
     66         "InactiveExitTimestamp": "Thu 2019-08-22 11:22:08 CST", 
     67         "InactiveExitTimestampMonotonic": "644109624078", 
     68         "JobTimeoutAction": "none", 
     69         "JobTimeoutUSec": "0", 
     70         "KillMode": "control-group", 
     71         "KillSignal": "15", 
     72         "LimitAS": "18446744073709551615", 
     73         "LimitCORE": "18446744073709551615", 
     74         "LimitCPU": "18446744073709551615", 
     75         "LimitDATA": "18446744073709551615", 
     76         "LimitFSIZE": "18446744073709551615", 
     77         "LimitLOCKS": "18446744073709551615", 
     78         "LimitMEMLOCK": "65536", 
     79         "LimitMSGQUEUE": "819200", 
     80         "LimitNICE": "0", 
     81         "LimitNOFILE": "4096", 
     82         "LimitNPROC": "31193", 
     83         "LimitRSS": "18446744073709551615", 
     84         "LimitRTPRIO": "0", 
     85         "LimitRTTIME": "18446744073709551615", 
     86         "LimitSIGPENDING": "31193", 
     87         "LimitSTACK": "18446744073709551615", 
     88         "LoadState": "loaded", 
     89         "MainPID": "20717", 
     90         "MemoryAccounting": "no", 
     91         "MemoryCurrent": "18446744073709551615", 
     92         "MemoryLimit": "18446744073709551615", 
     93         "MountFlags": "0", 
     94         "Names": "nginx.service", 
     95         "NeedDaemonReload": "no", 
     96         "Nice": "0", 
     97         "NoNewPrivileges": "no", 
     98         "NonBlocking": "no", 
     99         "NotifyAccess": "none", 
    100         "OOMScoreAdjust": "0", 
    101         "OnFailureJobMode": "replace", 
    102         "PIDFile": "/var/run/nginx.pid", 
    103         "PermissionsStartOnly": "no", 
    104         "PrivateDevices": "no", 
    105         "PrivateNetwork": "no", 
    106         "PrivateTmp": "no", 
    107         "ProtectHome": "no", 
    108         "ProtectSystem": "no", 
    109         "RefuseManualStart": "no", 
    110         "RefuseManualStop": "no", 
    111         "RemainAfterExit": "no", 
    112         "Requires": "basic.target", 
    113         "Restart": "no", 
    114         "RestartUSec": "100ms", 
    115         "Result": "success", 
    116         "RootDirectoryStartOnly": "no", 
    117         "RuntimeDirectoryMode": "0755", 
    118         "SameProcessGroup": "no", 
    119         "SecureBits": "0", 
    120         "SendSIGHUP": "no", 
    121         "SendSIGKILL": "yes", 
    122         "Slice": "system.slice", 
    123         "StandardError": "inherit", 
    124         "StandardInput": "null", 
    125         "StandardOutput": "journal", 
    126         "StartLimitAction": "none", 
    127         "StartLimitBurst": "5", 
    128         "StartLimitInterval": "10000000", 
    129         "StartupBlockIOWeight": "18446744073709551615", 
    130         "StartupCPUShares": "18446744073709551615", 
    131         "StatusErrno": "0", 
    132         "StopWhenUnneeded": "no", 
    133         "SubState": "running", 
    134         "SyslogLevelPrefix": "yes", 
    135         "SyslogPriority": "30", 
    136         "SystemCallErrorNumber": "0", 
    137         "TTYReset": "no", 
    138         "TTYVHangup": "no", 
    139         "TTYVTDisallocate": "no", 
    140         "TasksAccounting": "no", 
    141         "TasksCurrent": "18446744073709551615", 
    142         "TasksMax": "18446744073709551615", 
    143         "TimeoutStartUSec": "1min 30s", 
    144         "TimeoutStopUSec": "1min 30s", 
    145         "TimerSlackNSec": "50000", 
    146         "Transient": "no", 
    147         "Type": "forking", 
    148         "UMask": "0022", 
    149         "UnitFilePreset": "disabled", 
    150         "UnitFileState": "disabled", 
    151         "Wants": "network-online.target system.slice", 
    152         "WatchdogTimestamp": "Thu 2019-08-22 11:22:08 CST", 
    153         "WatchdogTimestampMonotonic": "644109632206", 
    154         "WatchdogUSec": "0"
    155     }
    156 }

      4.7  cron-模块

          用于管理设计任务

            包含如下选项

     1 backup:对远程主机上的原任务计划内容修改之前做备份 
     2 cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划 
     3 day:日(1-31,*,*/2,……) 
     4 hour:小时(0-23,*,*/2,……)  
     5 minute:分钟(0-59,*,*/2,……) 
     6 month:月(1-12,*,*/2,……) 
     7 weekday:周(0-7,*,……)
     8 job:要执行的任务,依赖于state=present 
     9 name:该任务的描述 
    10 special_time:指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourly 
    11 state:确认该任务计划是创建还是删除 
    12 user:以哪个用户的身份执行

      4.7.1 案例1-使用ansible执行远程的计划定时任务升级系统yum update

    1 [root@test-1 ansible]# ansible test -m cron -a 'name="yum update" minute=00 hour=02 day=* month=* weekday=* user=root job="yum update"'
    2 192.168.3.174 | CHANGED => {
    3     "changed": true, 
    4     "envs": [], 
    5     "jobs": [
    6         "yum update"
    7     ]
    8 }

        执行结果:

    1 [root@test-1 ansible]# ansible test -m command -a "crontab -l"
    2 192.168.3.174 | CHANGED | rc=0 >>
    3 #Ansible: yum update
    4 00 02 * * * yum update

       4.7.2 案例2-使用ansible执行远程计划定时任务执行脚本

     1 [root@test-1 scripts]# ansible web1 -m cron -a 'name="yum update" minute=02 hour=* day=* month=* weekday=1  user=root  job="/usr/bin/bash  /scripts/lnmp.sh >/dev/null 2>&1"'
     2 192.168.200.133 | CHANGED => {
     3     "ansible_facts": {
     4         "discovered_interpreter_python": "/usr/bin/python"
     5     }, 
     6     "changed": true, 
     7     "envs": [], 
     8     "jobs": [
     9         "yum update"
    10     ]
    11 }
    12 192.168.200.132 | CHANGED => {
    13     "ansible_facts": {
    14         "discovered_interpreter_python": "/usr/bin/python"
    15     }, 
    16     "changed": true, 
    17     "envs": [], 
    18     "jobs": [
    19         "yum update"
    20     ]
    21 }

       执行结果:

    1 [root@test-1 scripts]# ansible web1 -m command  -a "crontab -l"
    2 192.168.200.133 | CHANGED | rc=0 >>
    3 #Ansible: yum update
    4 02 * * * 1 /usr/bin/bash  /scripts/lnmp.sh >/dev/null 2>&1
    5 
    6 192.168.200.132 | CHANGED | rc=0 >>
    7 #Ansible: yum update
    8 02 * * * 1 /usr/bin/bash  /scripts/lnmp.sh >/dev/null 2>&1

     4.8  yum安装模块

    1 config_file:yum的配置文件 
    2 disable_gpg_check:关闭gpg_check 
    3 disablerepo:不启用某个源 
    4 enablerepo:启用某个源
    5 name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径 
    6 state:定义软件包状态
    7     present:安装
    8     absent:删除
    9     latest:安装最新的

     4.8.1 案例1-ansible远程执行安装http服务

     1 [root@test-1 ansible]# ansible test -m yum -a "name=httpd state=present"
     2 192.168.3.174 | CHANGED => {
     3     "ansible_facts": {
     4         "pkg_mgr": "yum"
     5     }, 
     6     "changed": true, 
     7     "msg": "", 
     8     "rc": 0, 
     9     "results": [
    10         "Loaded plugins: fastestmirror
    Loading mirror speeds from cached hostfile
     * base: centos.ustc.edu.cn
     * epel: mirrors.aliyun.com
     * extras: mirrors.cn99.com
     * updates: mirrors.aliyun.com
    Resolving Dependencies
    --> Running transaction check
    ---> Package httpd.x86_64 0:2.4.6-80.el7.centos.1 will be installed
    --> Processing Dependency: httpd-tools = 2.4.6-80.el7.centos.1 for package: httpd-2.4.6-80.el7.centos.1.x86_64
    --> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-80.el7.centos.1.x86_64
    --> Processing Dependency: libaprutil-1.so.0()(64bit) for package: httpd-2.4.6-80.el7.centos.1.x86_64
    --> Processing Dependency: libapr-1.so.0()(64bit) for package: httpd-2.4.6-80.el7.centos.1.x86_64
    --> Running transaction check
    ---> Package apr.x86_64 0:1.4.8-3.el7_4.1 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-80.el7.centos.1 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-80.el7.centos.1       updates       2.7 M
    Installing for dependencies:
     apr               x86_64       1.4.8-3.el7_4.1             base          103 k
     apr-util          x86_64       1.5.2-6.el7                 base           92 k
     httpd-tools       x86_64       2.4.6-80.el7.centos.1       updates        90 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                                              1.5 MB/s | 3.0 MB  00:01     
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : apr-1.4.8-3.el7_4.1.x86_64                                   1/5 
      Installing : apr-util-1.5.2-6.el7.x86_64                                  2/5 
      Installing : httpd-tools-2.4.6-80.el7.centos.1.x86_64                     3/5 
      Installing : mailcap-2.1.41-2.el7.noarch                                  4/5 
      Installing : httpd-2.4.6-80.el7.centos.1.x86_64                           5/5 
      Verifying  : mailcap-2.1.41-2.el7.noarch                                  1/5 
      Verifying  : httpd-tools-2.4.6-80.el7.centos.1.x86_64                     2/5 
      Verifying  : apr-util-1.5.2-6.el7.x86_64                                  3/5 
      Verifying  : apr-1.4.8-3.el7_4.1.x86_64                                   4/5 
      Verifying  : httpd-2.4.6-80.el7.centos.1.x86_64                           5/5 
    
    Installed:
      httpd.x86_64 0:2.4.6-80.el7.centos.1                                          
    
    Dependency Installed:
      apr.x86_64 0:1.4.8-3.el7_4.1                  apr-util.x86_64 0:1.5.2-6.el7   
      httpd-tools.x86_64 0:2.4.6-80.el7.centos.1    mailcap.noarch 0:2.1.41-2.el7   
    
    Complete!
    "
    11     ]
    12 }

        执行结果

    1 [root@test-1 ansible]# ansible test -m shell -a "rpm -qa |grep httpd"
    2 192.168.3.174 | CHANGED | rc=0 >>
    3 httpd-2.4.6-80.el7.centos.1.x86_64
    4 httpd-tools-2.4.6-80.el7.centos.1.x86_64

      4.8.2 案例2-ansible远程执行安装centos 7 epel源

     1 [root@test-1 ansible]# ansible test-3 -m yum -a "name='https://mirrors.aliyun.com/epel/epel-release-latest-7.noarch.rpm' state=present"
     2 192.168.3.175 | CHANGED => {
     3     "ansible_facts": {
     4         "pkg_mgr": "yum"
     5     }, 
     6     "changed": true, 
     7     "msg": "", 
     8     "rc": 0, 
     9     "results": [
    10         "Loaded plugins: fastestmirror
    Examining /root/.ansible/tmp/ansible-tmp-1542686869.36-173961956771252/epel-release-latest-7.noarchxjZ9vT.rpm: epel-release-7-11.noarch
    Marking /root/.ansible/tmp/ansible-tmp-1542686869.36-173961956771252/epel-release-latest-7.noarchxjZ9vT.rpm to be installed
    Resolving Dependencies
    --> Running transaction check
    ---> Package epel-release.noarch 0:7-11 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ================================================================================
     Package         Arch      Version Repository                              Size
    ================================================================================
    Installing:
     epel-release    noarch    7-11    /epel-release-latest-7.noarchxjZ9vT     24 k
    
    Transaction Summary
    ================================================================================
    Install  1 Package
    
    Total size: 24 k
    Installed size: 24 k
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : epel-release-7-11.noarch                                     1/1 
      Verifying  : epel-release-7-11.noarch                                     1/1 
    
    Installed:
      epel-release.noarch 0:7-11                                                    
    
    Complete!
    "
    11     ]
    12 }

        查看执行结果

    1 [root@test-1 ansible]# ansible test-3 -m shell -a 'rpm -qa |grep epel'
    2 192.168.3.175 | CHANGED | rc=0 >>
    3 epel-release-7-11.noarch

    4.9 group-模块

          group模块请求的是groupadd,groupdel,groupmod三个指令

    1 gid:指定组的gid
    2 name:指定用户组名
    3 state:是否创建还是删除
    4     present: (默认是创建用户)
    5     absent:删除用户
    6 system:是否为系统用户

      4.9.1  案例1-创建一个用户组

     1 [root@test-1 scripts]# ansible web1 -m group -a "name=www gid=1000 state=present"
     2 192.168.200.133 | CHANGED => {
     3     "ansible_facts": {
     4         "discovered_interpreter_python": "/usr/bin/python"
     5     }, 
     6     "changed": true, 
     7     "gid": 1000, 
     8     "name": "www", 
     9     "state": "present", 
    10     "system": false
    11 }
    12 192.168.200.132 | CHANGED => {
    13     "ansible_facts": {
    14         "discovered_interpreter_python": "/usr/bin/python"
    15     }, 
    16     "changed": true, 
    17     "gid": 1000, 
    18     "name": "www", 
    19     "state": "present", 
    20     "system": false
    21 }

        执行结果

    1   [root@test-1 scripts]# ansible web1 -m shell -a "tail -1 /etc/group"
    2   192.168.200.132 | CHANGED | rc=0 >>
    3   www:x:1000:
    4 
    5   192.168.200.133 | CHANGED | rc=0 >>
    6   www:x:1000:

    4.10 user用户模块

            user模块是请求的是useradd, userdel, usermod三个指令

     1   - name: 管理用户帐号
     2   action: user
     3   comment          # 用户的描述信息
     4   createhome       # 是否创建家目录
     5   force            # 在使用`state=absent'是, 行为与`userdel --force'一致.
     6   group            # 指定基本组
     7   groups           # 指定附加组,如果指定为('groups=')表示删除所有组
     8   home             # 指定用户家目录
     9   login_class      #可以设置用户的登录类 FreeBSD, OpenBSD and NetBSD系统.
    10   move_home        # 如果设置为`home='时, 试图将用户主目录移动到指定的目录
    11   name=            # 指定用户名
    12   non_unique       # 该选项允许改变非唯一的用户ID值
    13   password         # 指定用户密码
    14   remove           # 在使用 `state=absent'时, 行为是与 `userdel --remove'一致.
    15   shell            # 指定用户的shell环境,默认是没有bash,指定系统用户的时候,是有bash环境
    16   state            #设置帐号状态,不指定为创建,指定值为absent表示删除
    17   system           # 当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户。
    18   uid              #指定用户的uid
    19   update_password  # 更新用户密码

      4.10.1 案例1-使用ansible远程执行创建一个普通用户,uid为1000,password为123456,创建家目录,指定/bin/bash

     1   [root@test-1 .ssh]# ansible test-2 -m user -a 'name=www groups=www password=123456  createhome=yes home=/home/www state=present shell=/bin/bash'
     2    [WARNING]: The input password appears not to have been hashed. The 'password' argument must be encrypted for this module to work properly.
     3 
     4   192.168.3.174 | CHANGED => {
     5       "changed": true, 
     6       "comment": "", 
     7       "create_home": true, 
     8       "group": 1001, 
     9       "groups": "www", 
    10       "home": "/home/www", 
    11       "name": "www1", 
    12       "password": "NOT_LOGGING_PASSWORD", 
    13       "shell": "/bin/bas", 
    14       "state": "present", 
    15       "stderr": "useradd: warning: the home directory already exists.
    Not copying any file from skel directory into it.
    ", 
    16       "stderr_lines": [
    17           "useradd: warning: the home directory already exists.", 
    18           "Not copying any file from skel directory into it."
    19       ], 
    20       "system": false, 
    21       "uid": 1001
    22   }

       上面黄色标记的提示警告,输入的明文的密码,用户创建成功了,但是密码不对

     1   ####利用ansible的user模块状态用户时要注意在password参数的后边添加密文,否则不能登陆用户 
     2   #通过Python的pip程序安装passlib即可为密码加密
     3 
     4   #安装Python2的pip工具,并通过pip工具安装Python的加密模块来给密码加密
     5   [root@ansible ~]# yum -y install python2-pip
     6   [root@ansible ~]# pip install passlib
     7   Collecting passlib
     8     Downloading https://files.pythonhosted.org/packages/ee/a7/d6d238d927df355d4e4e000670342ca4705a72f0bf694027cf67d9bcf5af/passlib-1.7.1-py2.py3-none-any.whl (498kB)
     9       100% |████████████████████████████████| 501kB 36kB/s 
    10   Installing collected packages: passlib
    11   Successfully installed passlib-1.7.1
    12   [root@test-1 .ssh]# python -c "from passlib.hash import sha512_crypt;import getpass;print sha512_crypt.encrypt(getpass.getpass())"
    13   Password:          #这里测试,输入的密码为123456
    14   $6$rounds=656000$9EdjgslzEasKjuhu$cnHjbtbcaAWBvMbJ/R6PI340gcP.6hmohFESkul5KXswtou/QO3trYJO9Ukkb3qHKw7.YGlFgL2..0b6RCxgm.     #这是加密后的密码

       再次重新执行验证

     1 [root@test-1 .ssh]# ansible test-2 -m user -a 'name=www groups=www password=$6$rounds=656000$9EdjgslzEasKjuhu$cnHjbtbcaAWBvMbJ/R6PI340gcP.6hmohFESkul5KXswtou/QO3trYJO9Ukkb3qHKw7.YGlFgL2..0b6RCxgm.  createhome=yes home=/home/www state=present shell=/bin/bash'
     2   192.168.3.174 | CHANGED => {
     3       "append": false, 
     4       "changed": true, 
     5       "comment": "", 
     6       "group": 100, 
     7       "groups": "www", 
     8       "home": "/home/www", 
     9       "move_home": false, 
    10       "name": "www", 
    11       "password": "NOT_LOGGING_PASSWORD", 
    12       "shell": "/bin/bash", 
    13       "state": "present", 
    14       "uid": 1000
    15   }

       查看执行后的结果

     1   [root@test-1 .ssh]# ansible test-2 -m command -a 'tail /etc/passwd'
     2   192.168.3.174 | CHANGED | rc=0 >>
     3   dbus:x:81:81:System message bus:/:/sbin/nologin
     4   polkitd:x:999:998:User for polkitd:/:/sbin/nologin
     5   sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
     6   postfix:x:89:89::/var/spool/postfix:/sbin/nologin
     7   chrony:x:998:996::/var/lib/chrony:/sbin/nologin
     8   saslauth:x:997:76:Saslauthd user:/run/saslauthd:/sbin/nologin
     9   nginx:x:996:995:nginx user:/var/cache/nginx:/sbin/nologin
    10   apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
    11   www:x:1000:100::/home/www:/bin/bash

     4.11 synchronize-模块

             使用rsync同步文件,其参数如下:

     1   archive: 归档,相当于同时开启recursive(递归)、links、perms、times、owner、group、-D选项都为yes ,默认该项为开启
     2   checksum: 跳过检测sum值,默认关闭
     3   compress:是否开启压缩
     4   copy_links:复制链接文件,默认为no ,注意后面还有一个links参数
     5   delete: 删除不存在的文件,默认no
     6   dest:目录路径
     7   dest_port:默认目录主机上的端口 ,默认是22,走的ssh协议
     8   dirs:传速目录不进行递归,默认为no,即进行目录递归
     9   rsync_opts:rsync参数部分(-avz)等参数
    10   set_remote_user:主要用于/etc/ansible/hosts中定义或默认使用的用户与rsync使用的用户不同的情况
    11   mode: push或pull 模块,push模的话,一般用于从本机向远程主机上传文件,pull 模式用于从远程主机上取文件
    12   src:源目录路径
    13   rsync_path:指定rsync的执行文件路径

      4.11.1 案例1-ansible同步目录文件测试

     1   [root@test-1 src]# touch /tmp/hello
     2   [root@test-1 src]# vim /tmp/hello
     3   [root@test-1 src]# ansible test-2 -m synchronize -a 'src=/tmp/hello dest=/tmp/'
     4   192.168.3.174 | CHANGED => {
     5       "changed": true, 
     6       "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh=/usr/bin/ssh -S none -i /root/.ssh/id_rsa -o Port=22 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --out-format=<<CHANGED>>%i %n%L /tmp/hello 192.168.3.174:/tmp/", 
     7       "msg": "<f+++++++++ hello
    ", 
     8       "rc": 0, 
     9       "stdout_lines": [
    10           "<f+++++++++ hello"
    11       ]
    12   }

          执行结果

    1   [root@test-1 src]# ansible test-2 -m command -a 'ls -lh /tmp/hello'
    2   192.168.3.174 | CHANGED | rc=0 >>
    3   -rw-r--r--. 1 root root 6 Nov 20 03:15 /tmp/hello

     4.11.2 案例2-ansible执行从本地向远程服务器上传文件

     1   [root@test-1 src]# ansible test-2 -m synchronize -a 'src=/usr/local/src/ dest=/usr/local/src/ dirs=no dest_port=22 mode=push delete=yes'
     2   192.168.3.174 | CHANGED => {
     3       "changed": true, 
     4       "cmd": "/usr/bin/rsync --delay-updates -F --compress --delete-after --archive --rsh=/usr/bin/ssh -S none -i /root/.ssh/id_rsa -o Port=22 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --out-format=<<CHANGED>>%i %n%L /usr/local/src/ 192.168.3.174:/usr/local/src/", 
     5       "msg": ".d..t...... ./
    <f+++++++++ boost_1_59_0.tar.gz
    <f+++++++++ mysql-5.7.22.tar.gz
    <f+++++++++ nginx-1.14.0.tar.gz
    <f+++++++++ php-7.2.6.tar.gz
    ", 
     6       "rc": 0, 
     7       "stdout_lines": [
     8           ".d..t...... ./", 
     9           "<f+++++++++ boost_1_59_0.tar.gz", 
    10           "<f+++++++++ mysql-5.7.22.tar.gz", 
    11           "<f+++++++++ nginx-1.14.0.tar.gz", 
    12           "<f+++++++++ php-7.2.6.tar.gz"
    13       ]
    14   }

        执行结果

    1   [root@test-1 src]# ansible test-2 -m command -a 'ls -lh /usr/local/src'
    2   192.168.3.174 | CHANGED | rc=0 >>
    3   total 149M
    4   -rw-r--r--. 1 root root  80M Oct 23 01:47 boost_1_59_0.tar.gz
    5   -rw-r--r--. 1 root root  50M Oct 22 22:57 mysql-5.7.22.tar.gz
    6   -rw-r--r--. 1 root root 993K Apr 17  2018 nginx-1.14.0.tar.gz
    7   -rw-r--r--. 1 root root  19M Oct 23 21:43 php-7.2.6.tar.gz

     4.11.3  案例3-ansible执行同步案例命令使用

     1   [root@test-1 src]# ansible test-2 -m synchronize -a 'src=/usr/local/src/ dest=/usr/local/src/ dirs=no dest_port=22 mode=push delete=yes rsync_path=/usr/bin/rsync rsync_opts="-avz"'
     2   192.168.3.174 | CHANGED => {
     3       "changed": true, 
     4       "cmd": "/usr/bin/rsync --delay-updates -F --compress --delete-after --archive --rsh=/usr/bin/ssh -S none -i /root/.ssh/id_rsa -o Port=22 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --rsync-path=/usr/bin/rsync -avz --out-format=<<CHANGED>>%i %n%L /usr/local/src/ 192.168.3.174:/usr/local/src/", 
     5       "msg": "building file list ... done
    .d..t...... ./
    <f+++++++++ boost_1_59_0.tar.gz
    <f+++++++++ mysql-5.7.22.tar.gz
    <f+++++++++ nginx-1.14.0.tar.gz
    <f+++++++++ php-7.2.6.tar.gz
    
    sent 153,090,035 bytes  received 98 bytes  23,552,328.15 bytes/sec
    total size is 156,206,518  speedup is 1.02
    ", 
     6       "rc": 0, 
     7       "stdout_lines": [
     8           "building file list ... done", 
     9           ".d..t...... ./", 
    10           "<f+++++++++ boost_1_59_0.tar.gz", 
    11           "<f+++++++++ mysql-5.7.22.tar.gz", 
    12           "<f+++++++++ nginx-1.14.0.tar.gz", 
    13           "<f+++++++++ php-7.2.6.tar.gz", 
    14           "sent 153,090,035 bytes  received 98 bytes  23,552,328.15 bytes/sec", 
    15           "total size is 156,206,518  speedup is 1.02"
    16       ]
    17   }

         执行结果

    1    [root@test-1 src]# ansible test-2 -m command -a 'ls -lh /usr/local/src'
    2    192.168.3.174 | CHANGED | rc=0 >>
    3    total 149M
    4    -rw-r--r--. 1 root root  80M Oct 23 01:47 boost_1_59_0.tar.gz
    5    -rw-r--r--. 1 root root  50M Oct 22 22:57 mysql-5.7.22.tar.gz
    6    -rw-r--r--. 1 root root 993K Apr 17  2018 nginx-1.14.0.tar.gz
    7    -rw-r--r--. 1 root root  19M Oct 23 21:43 php-7.2.6.tar.gz

      4.12 filesystem-模块

        在块设备上创建文件系统

    1   dev:目标块设备
    2   force:在一个已有文件系统 的设备上强制创建
    3   fstype:文件系统的类型
    4   opts:传递给mkfs命令的选项

     4.12.1 案例

    1     ansible test -m filesystem -a 'fstype=ext3 dev=/dev/sdb1 force=yes'
    2     ansible test -m filesystem -a 'fstype=ext4 dev=/dev/sdb1 opts="-cc"'

       4.13 mount-模块

               配置挂载点

     1   dump
     2   fstype:必选项,挂载文件的类型 
     3   name:必选项,挂载点 
     4   opts:传递给mount命令的参数
     5   src:必选项,要挂载的文件 
     6   state:必选项 
     7       present:只处理fstab中的配置 
     8       absent:删除挂载点 
     9       mounted:自动创建挂载点并挂载之 
    10   umounted:卸载

      4.13.1 创建挂载示例

    1   ansible test -a 'dd if=/dev/zero of=/disk.img bs=4k count=1024'
    2   ansible test -a 'losetup /dev/loop0 /disk.img'
    3   ansible test -m filesystem 'fstype=ext4 force=yes opts=-F dev=/dev/loop0'
    4   ansible test -m mount 'name=/mnt src=/dev/loop0 fstype=ext4 state=mounted opts=rw'

     4.14 get_url模块

              该模块主要用于从http、ftp、https服务器上下载文件(类似与wget)

    1     sha256sum:下载完成后进行sha256 check;
    2     timeout:下载超时时间,默认10s
    3     url:下载的URL
    4     url_password、url_username:主要用于需要用户名密码进行验证的情况
    5     use_proxy:是事使用代理,代理需事先在环境变更中定义
    6     dest:指定保存的目录

     4.14.1 案例1-url下nginx包

     1       [root@test-1 src]# ansible test-2 -m get_url -a "url=http://nginx.org/download/nginx-1.14.1.tar.gz dest=/usr/local/src"
     2       192.168.3.174 | CHANGED => {
     3           "changed": true, 
     4           "checksum_dest": null, 
     5           "checksum_src": "a9dc8c5b055a3f0021d09c112d27422f45dd439c", 
     6           "dest": "/usr/local/src/nginx-1.14.1.tar.gz", 
     7           "gid": 0, 
     8           "group": "root", 
     9           "md5sum": "18561561ffa2b63885b607453390b49c", 
    10           "mode": "0644", 
    11           "msg": "OK (1014040 bytes)", 
    12           "owner": "root", 
    13           "secontext": "system_u:object_r:usr_t:s0", 
    14           "size": 1014040, 
    15           "src": "/root/.ansible/tmp/ansible-tmp-1542766406.28-80553441492405/tmpe_tiWK", 
    16           "state": "file", 
    17           "status_code": 200, 
    18           "uid": 0, 
    19           "url": "http://nginx.org/download/nginx-1.14.1.tar.gz"
    20      }

         查看执行结果

    1     [root@test-1 src]# ansible test-2 -m shell -a 'ls /usr/local/src'
    2     192.168.3.174 | CHANGED | rc=0 >>
    3     nginx-1.14.1.tar.gz

     4.15 unarchive-解压模块

    1     copy:在解压文件之前,是否先将文件复制到远程主机,默认为yes。若为no,则要求目标主机上压缩包必须存在。
    2     creates:指定一个文件名,当该文件存在时,则解压指令不执行
    3     dest:远程主机上的一个路径,即文件解压的路径 
    4     grop:解压后的目录或文件的属组
    5     list_files:如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项
    6     mode:解决后文件的权限
    7     src:如果copy为yes,则需要指定压缩文件的源路径 
    8     owner:解压后文件或目录的属主

      4.15.1 案例1-ansible从本地解压到目标服务器上,指定路径

     1     [root@test-1 scripts]# ansible localhost -m unarchive -a "src=/usr/local/src/nginx-1.16.1.tar.gz  dest=/usr/local/src/"
     2   192.168.200.131 | CHANGED => {
     3       "ansible_facts": {
     4           "discovered_interpreter_python": "/usr/bin/python"
     5       }, 
     6       "changed": true, 
     7       "dest": "/usr/local/src/", 
     8       "extract_results": {
     9           "cmd": [
    10               "/usr/bin/gtar", 
    11               "--extract", 
    12               "-C", 
    13               "/usr/local/src/", 
    14               "-z", 
    15               "-f", 
    16               "/root/.ansible/tmp/ansible-tmp-1566460438.03-170976243195560/source"
    17           ], 
    18           "err": "", 
    19           "out": "", 
    20           "rc": 0
    21       }, 
    22       "gid": 0, 
    23       "group": "root", 
    24       "handler": "TgzArchive", 
    25       "mode": "0755", 
    26       "owner": "root", 
    27       "size": 53, 
    28       "src": "/root/.ansible/tmp/ansible-tmp-1566460438.03-170976243195560/source", 
    29       "state": "directory", 
    30       "uid": 0
    31   }

        执行结果查看

    1   [root@test-1 scripts]# ansible localhost -m shell -a "ls -a /usr/local/src/"
    2   192.168.200.131 | CHANGED | rc=0 >>
    3   .
    4   ..
    5   nginx-1.16.1
    6   nginx-1.16.1.tar.gz

     4.16  raw模块

          类似于shell模块,支持管道

      4.16.1 案例使用raw查看

     1   [root@test-1 scripts]# ansible localhost -m raw -a "ls -a /usr/local/src/"
     2   192.168.200.131 | CHANGED | rc=0 >>
     3   .  ..  nginx-1.16.1  nginx-1.16.1.tar.gz
     4   Shared connection to 192.168.200.131 closed.
     5 
     6 
     7   [root@test-1 scripts]# ansible web1 -m raw -a "netstat -lntup|grep 80"
     8   192.168.200.132 | CHANGED | rc=0 >>
     9   tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      20648/nginx: master 
    10   Shared connection to 192.168.200.132 closed.
    11 
    12 
    13   192.168.200.133 | CHANGED | rc=0 >>
    14   tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      20717/nginx: master 
    15   Shared connection to 192.168.200.133 closed.

     4.17 script脚本模块

    1   - name: 将本地脚本复制到远程主机并运行之
    2   action: script
    3   creates      # 一个文件名,当这个文件存在,则该命令不执行
    4   free_form=   # 本地脚本路径
    5   removes      # 一个文件名,这个文件不存在,则该命令不执行

      4.17.1 案例将本地脚本复制到远程主机并运行

       创建测试执行脚本

    1   [root@test-1 scripts]# vim /scripts/lnmp.sh
    2   [root@test-1 scripts]# cat /scripts/lnmp.sh
    3   echo "ansible is lnmp"

     ansible远程执行

     1   [root@test-1 scripts]# ansible web1 -m script  -a "/scripts/lnmp.sh"
     2   192.168.200.132 | CHANGED => {
     3       "changed": true, 
     4       "rc": 0, 
     5       "stderr": "Shared connection to 192.168.200.132 closed.
    ", 
     6       "stderr_lines": [
     7           "Shared connection to 192.168.200.132 closed."
     8       ], 
     9       "stdout": "ansible is lnmp
    ", 
    10       "stdout_lines": [
    11           "ansible is lnmp"
    12       ]
    13   }
    14   192.168.200.133 | CHANGED => {
    15       "changed": true, 
    16       "rc": 0, 
    17       "stderr": "Shared connection to 192.168.200.133 closed.
    ", 
    18       "stderr_lines": [
    19           "Shared connection to 192.168.200.133 closed."
    20       ], 
    21       "stdout": "ansible is lnmp
    ", 
    22       "stdout_lines": [
    23           "ansible is lnmp"
    24       ]
    25   }

     注释:

       黄色输出的是,脚本编写内容

     4.18 setup收集指定服务器的信息

            收集指定服务器的信息,每个被管理节点在接收并运行管理命令之前,会将自己主机相关信息,如操作系统版本、IP地址等报告给远程的ansbile主机.在playbooks里经常会用到的一个参数gather_facts就与该模块相关。setup模块下经常使用的一个参数是filter参数,具体使用示例如下:

     1 [root@test-1 scripts]# ansible-doc -s setup
     2 - name: Gathers facts about remote hosts
     3   setup:
     4       fact_path:             # path used for local ansible facts (`*.fact') - files in this dir will be run (if executable) and their results
     5                                be added to `ansible_local' facts if a file is not executable it is read. Check
     6                                notes for Windows options. (from 2.1 on) File/results format can be JSON or INI-
     7                                format. The default `fact_path' can be specified in `ansible.cfg' for when setup
     8                                is automatically called as part of `gather_facts'.
     9       filter:                # if supplied, only return facts that match this shell-style (fnmatch) wildcard.
    10       gather_subset:         # if supplied, restrict the additional facts collected to the given subset. Possible values: `all', `min',
    11                                `hardware', `network', `virtual', `ohai', and `facter'. Can specify a list of
    12                                values to specify a larger subset. Values can also be used with an initial `!' to
    13                                specify that that specific subset should not be collected.  For instance:
    14                                `!hardware,!network,!virtual,!ohai,!facter'. If `!all' is specified then only the
    15                                min subset is collected. To avoid collecting even the min subset, specify
    16                                `!all,!min'. To collect only specific facts, use `!all,!min', and specify the
    17                                particular fact subsets. Use the filter parameter if you do not want to display
    18                                some collected facts.
    19       gather_timeout:        # Set the default timeout in seconds for individual fact gathering

      4.18.1 ansible的setup常用模块

    ansible_all_ipv4_addresses:仅显示ipv4的信息
    
    ansible_devices:仅显示磁盘设备信息
    
    ansible_distribution:显示是什么系统,例:centos,suse等
    
    ansible_distribution_major_version:显示是系统主版本
    
    ansible_distribution_version:仅显示系统版本
    
    ansible_machine:显示系统类型,例:32位,还是64位
    
    ansible_eth0:仅显示eth0的信息
    
    ansible_hostname:仅显示主机名
    
    ansible_kernel:仅显示内核版本
    
    ansible_lvm:显示lvm相关信息
    
    ansible_memtotal_mb:显示系统总内存
    
    ansible_memfree_mb:显示可用系统内存
    
    ansible_memory_mb:详细显示内存情况
    
    ansible_swaptotal_mb:显示总的swap内存
    
    ansible_swapfree_mb:显示swap内存的可用内存
    
    ansible_mounts:显示系统磁盘挂载情况
    
    ansible_processor:显示cpu个数(具体显示每个cpu的型号)
    
    ansible_processor_vcpus:显示cpu个数(只显示总的个数)
    
    ansible_python_version:显示python版本

      4.18.2 执行案例

    1 ansible 10.212.52.252 -m setup -a 'filter=ansible_*_mb'   //查看主机内存信息
    2 ansible 10.212.52.252 -m setup -a 'filter=ansible_eth[0-2]'   //查看地接口为eth0-2的网卡信息
    3 ansible all -m setup --tree /tmp/facts   //将所有主机的信息输入到/tmp/facts目录下,每台主机的信息输入到主机名文件中(/etc/ansible/hosts里的主机名)
  • 相关阅读:
    软件新人问题解答(一)
    项目上线流程
    面试题:如何测试登录功能
    软件测试人员在工作中如何运用Linux
    认识接口测试
    刚入职的新人如何快速了解公司业务
    软件测试人员每天的工作日常
    面试题分析(二)如何避免漏测
    [谨记]记线上事故并分析原因
    面试经验分享:遇到不会回答的问题怎么回答才好
  • 原文地址:https://www.cnblogs.com/scajy/p/11389766.html
Copyright © 2011-2022 走看看