ansible-經常使用模塊

1. ansible-經常使用模塊
    根據官方的分類,將模塊按功能分類爲:雲模塊、命令模塊、數據庫模塊、文件模塊、資產模塊、消息模塊、監控模塊、網絡模塊、通知模塊、包管理模塊、源碼控制模塊、系統模塊、單元模塊、web設施模塊、windows模塊php

  • 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.模塊的使用node

 查看模塊幫助python

1 [root@test-1 bin]# ansible-doc -l #查看全部模塊 2 [root@test-1 bin]#ansible-doc -s MODULE_NAME         #查看指定模塊的詳細幫助

3.ansible命令應用基礎mysql

   使用語法:linux

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

   註釋:nginx

  • -f   forks:啓動的併發線程數
  • -m module_name:  要使用的模塊
  • -a  args:模塊特有的參數

4.模塊使用案例web

 4.1 ping模塊sql

    測試主機是否通的,用法很簡單,若是成功就返回的是pong。shell

 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\nLoading mirror speeds from cached hostfile\n * base: centos.ustc.edu.cn\n * epel: mirrors.aliyun.com\n * extras: mirrors.cn99.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-80.el7.centos.1 will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-80.el7.centos.1 for package: httpd-2.4.6-80.el7.centos.1.x86_64\n--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-80.el7.centos.1.x86_64\n--> Processing Dependency: libaprutil-1.so.0()(64bit) for package: httpd-2.4.6-80.el7.centos.1.x86_64\n--> Processing Dependency: libapr-1.so.0()(64bit) for package: httpd-2.4.6-80.el7.centos.1.x86_64\n--> Running transaction check\n---> Package apr.x86_64 0:1.4.8-3.el7_4.1 will be installed\n---> Package apr-util.x86_64 0:1.5.2-6.el7 will be installed\n---> Package httpd-tools.x86_64 0:2.4.6-80.el7.centos.1 will be installed\n---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n httpd x86_64 2.4.6-80.el7.centos.1 updates 2.7 M\nInstalling for dependencies:\n apr x86_64 1.4.8-3.el7_4.1 base 103 k\n apr-util x86_64 1.5.2-6.el7 base 92 k\n httpd-tools x86_64 2.4.6-80.el7.centos.1 updates 90 k\n mailcap noarch 2.1.41-2.el7 base 31 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package (+4 Dependent packages)\n\nTotal download size: 3.0 M\nInstalled size: 10 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal 1.5 MB/s | 3.0 MB 00:01 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : apr-1.4.8-3.el7_4.1.x86_64 1/5 \n Installing : apr-util-1.5.2-6.el7.x86_64 2/5 \n Installing : httpd-tools-2.4.6-80.el7.centos.1.x86_64 3/5 \n Installing : mailcap-2.1.41-2.el7.noarch 4/5 \n Installing : httpd-2.4.6-80.el7.centos.1.x86_64 5/5 \n Verifying : mailcap-2.1.41-2.el7.noarch 1/5 \n Verifying : httpd-tools-2.4.6-80.el7.centos.1.x86_64 2/5 \n Verifying : apr-util-1.5.2-6.el7.x86_64 3/5 \n Verifying : apr-1.4.8-3.el7_4.1.x86_64 4/5 \n Verifying : httpd-2.4.6-80.el7.centos.1.x86_64 5/5 \n\nInstalled:\n httpd.x86_64 0:2.4.6-80.el7.centos.1 \n\nDependency Installed:\n apr.x86_64 0:1.4.8-3.el7_4.1 apr-util.x86_64 0:1.5.2-6.el7 \n httpd-tools.x86_64 0:2.4.6-80.el7.centos.1 mailcap.noarch 0:2.1.41-2.el7 \n\nComplete!\n"
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\nExamining /root/.ansible/tmp/ansible-tmp-1542686869.36-173961956771252/epel-release-latest-7.noarchxjZ9vT.rpm: epel-release-7-11.noarch\nMarking /root/.ansible/tmp/ansible-tmp-1542686869.36-173961956771252/epel-release-latest-7.noarchxjZ9vT.rpm to be installed\nResolving Dependencies\n--> Running transaction check\n---> Package epel-release.noarch 0:7-11 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n epel-release noarch 7-11 /epel-release-latest-7.noarchxjZ9vT 24 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal size: 24 k\nInstalled size: 24 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : epel-release-7-11.noarch 1/1 \n Verifying : epel-release-7-11.noarch 1/1 \n\nInstalled:\n epel-release.noarch 0:7-11 \n\nComplete!\n"
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.\nNot copying any file from skel directory into it.\n", 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\n",  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...... ./\n<f+++++++++ boost_1_59_0.tar.gz\n<f+++++++++ mysql-5.7.22.tar.gz\n<f+++++++++ nginx-1.14.0.tar.gz\n<f+++++++++ php-7.2.6.tar.gz\n",  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\n.d..t...... ./\n<f+++++++++ boost_1_59_0.tar.gz\n<f+++++++++ mysql-5.7.22.tar.gz\n<f+++++++++ nginx-1.14.0.tar.gz\n<f+++++++++ php-7.2.6.tar.gz\n\nsent 153,090,035 bytes received 98 bytes 23,552,328.15 bytes/sec\ntotal size is 156,206,518 speedup is 1.02\n",  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.\r\n",  6       "stderr_lines": [  7           "Shared connection to 192.168.200.132 closed."
 8    ],  9       "stdout": "ansible is lnmp\r\n", 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.\r\n", 18       "stderr_lines": [ 19           "Shared connection to 192.168.200.133 closed."
20    ], 21       "stdout": "ansible is lnmp\r\n", 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裏的主機名)
相關文章
相關標籤/搜索