1. 程式人生 > >詳解Ansible服務常用命令模塊

詳解Ansible服務常用命令模塊

for provided 星期 run -i 目標 module systemd example

ansible可以使用命令行方式進行自動化管理,基本語法如下:

ansible 主機名 -m 模塊名稱 -a 模塊特有參數

ansible的命令行管理工具都是由一系列模塊、參數所支持的,可以在命令後面加上-h或--help獲取幫助。如使用ansible-doc -h或者ansible-doc --help查看其幫助信息
ansible-doc是用來查看模塊幫助信息的工具,最主要的選項 -l用來列出可使用的模塊, -s用來列出某個模塊的描述信息和使用示例。

以下是我列出yum模塊的描述信息和操作動作:

[root@promote ~]# ansible-doc -s yum
- name: Manages packages with the `yum‘ package manager
  yum:
      allow_downgrade:       # Specify if the named package and version is
                               allowed to
                               downgrade a maybe
                               already installed
                               higher version of
                               that package.
                               Note that setting
                               allow_downgrade=T
                               rue can make this
                               module behave in
                               a non-idempotent
                               way.

Ansible自帶了很多模塊,能夠下發執行Ansible的各種管理任務。下面我列出一些較為常用的模塊。
1 command模塊
ansible管理工具使用-m選項來指定使用模塊,默認使用command模塊,即-m選項省略時會運行次模塊,用於在被管理主機上運行命令

[root@promote ~]# ansible-doc -s command
- name: Executes a command on a remote node
  command:
      argv:                  # Allows the user to provide the command as a list
                               vs. a string.
                               Only the string
                               or the list form
                               can be provided,
                               not both.  One or
                               the other must be
                               provided.
      chdir:                 # Change into this directory before running the
                               command.
      creates:               # A filename or (since 2.0) glob pattern. If it
                               already exists,
                               this step *won‘t*
                               be run.
ansible-doc -l    #列出所有已安裝的模塊 註:按q退出
ansible-doc -s yum    #-s列出yum模塊描述信息和操作動作
ansible 192.168.199.130 -m command -a ‘date‘    #指定IP執行date
ansible web -m command -a ‘date‘    #指定分類執行date
ansible all -m command -a ‘date‘    #所有hosts主機執行date
ansible all -a ‘ls /‘    #如果不加-m模塊,則默認運行command模塊

下面我在ansible服務器上執行‘date’命令來查看被管理主機的時間:

[root@promote ~]# ansible all -a ‘date‘
192.168.199.131 | CHANGED | rc=0 >>
2018年 10月 22日 星期一 22:35:53 CST

192.168.199.130 | CHANGED | rc=0 >>
2018年 10月 22日 星期一 22:35:53 CST

2 cron 模塊
Ansible中的cron模塊用於定義計劃任務。其中兩種狀態(state):present表示添加(省略狀態時默認使用),absent表示移除

[root@promote ~]# ansible-doc -s cron              #查看cron模塊信息
- name: Manage cron.d and crontab entries
  cron:
      backup:                # If set, create a backup of the crontab before it
                               is modified. The
                               location of the
                               backup is
                               returned in the
                               `backup_file‘
                               variable by this
                               module.
......

添加任務計劃:

[root@promote ~]# ansible web -m cron -a ‘minute="*/1" job="/usr/bin/echo hehe" name="test hehe"‘
192.168.199.130 | SUCCESS => {
    "changed": false, 
    "envs": [], 
    "jobs": [
        "test hehe"
    ]
}
[root@promote ~]# ansible web -a ‘crontab -l‘            #查看web主機的計劃性任務
192.168.199.130 | CHANGED | rc=0 >>
#Ansible: test hehe
*/1 * * * * /usr/bin/echo hehe

移除任務計劃:

[root@promote ~]# ansible web -m cron -a ‘name="test hehe" state=absent‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
[root@promote ~]# ansible web -a ‘crontab -l‘
192.168.199.130 | CHANGED | rc=0 >>

3 user模塊
ansible中的user模塊用於創建新用戶和更改,刪除已存在的用戶,其中name項用來指明創建的用戶名稱
user模塊是請求的是useadd,userdel,usermod三個指令

創建一個名為test01的用戶:

[root@promote ~]# ansible all -m user -a ‘name=test01‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/test01", 
    "name": "test01", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}

刪除test01用戶:

[root@promote ~]# ansible all -m user -a ‘name=test01 state=absent‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "force": false, 
    "name": "test01", 
    "remove": false, 
    "state": "absent"
}

4 group 模塊
ansible中的group模塊用於對用戶組進行管理
group模塊請求的是groupadd,groupdel,groupmod三個指令

[root@promote ~]# ansible-doc -s group
- name: Add or remove groups
 group:
 gid:                   # Optional `GID‘ to set for the group.
 name:                  # (required) Name of the group to manage.
 state:                 # Whether the group should be present or not onthe remote host.
 system:                # If `yes‘, indicates that the group created is asystem group.

下面我創建mysql組,將mysql用戶添加到mysql組中

[root@promote ~]# ansible web -m group -a ‘name=mysql gid=306 system=yes‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "gid": 306, 
    "name": "mysql", 
    "state": "present", 
    "system": true
}
[root@promote ~]# ansible web -m user -a ‘name=mysql uid=306 system=yes group=mysql‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 306, 
    "home": "/home/mysql", 
    "name": "mysql", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": true, 
    "uid": 306
}

5 copy 模塊
ansible中的copy模塊用於實現文件復制和批量下發文件。其中使用src來定義本地源文件路徑,使用dest定義被管理主機文件路徑,使用content則是通過指定信息內容生成目標文件。

[root@promote ~]# ansible-doc -s copy                  #查看copy模塊指令
- name: Copies files to remote locations
  copy:
      attributes:            # Attributes the file or directory should have. To get
                               supported flags look
                               at the man page for
                               `chattr‘ on the target
                               system. This string
                               should contain the
                               attributes in the same
                               order as the one
                               displayed by `lsattr‘.
                               `=‘ operator is
                               assumed as default,
                               otherwise `+‘ or `-‘
                               operators need to be
                               included in the
                               string.

下面我將本地文件/etc/fstab復制到被管理主機上的/opt/fstab.bk,所有者設置為root,權限設置為640

[root@promote ~]# ansible web -m copy -a ‘src=/etc/fstab dest=/opt/fstab.bk owner=root mode=644‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "checksum": "a8b8566b1d9f28b55823c8f61f88d35d81014418", 
    "dest": "/opt/fstab.bk", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f25dda38d8c7bb5988c8607bc2a9a17b", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 595, 
    "src": "/root/.ansible/tmp/ansible-tmp-1540220785.51-128147354820010/source", 
    "state": "file", 
    "uid": 0
}
[root@web ~]# ll /opt/fstab.bk 
-rw-r--r--. 1 root root 595 10月 22 23:06 /opt/fstab.bk

接著我將"hello"寫入“/opt/fstab.bk”

[root@promote ~]# ansible web -m copy -a ‘content="hello!" dest=/opt/fstab.bk‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "checksum": "8f7d88e901a5ad3a05d8cc0de93313fd76028f8c", 
    "dest": "/opt/fstab.bk", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "5a8dd3ad0756a93ded72b823b19dd877", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 6, 
    "src": "/root/.ansible/tmp/ansible-tmp-1540221051.34-78743719487515/source", 
    "state": "file", 
    "uid": 0
}
[root@web ~]# cat /opt/fstab.bk 
hello!

6 file 模塊
在ansible中使用file模塊來設置文件屬性。其中使用path指定文件路徑,使用src定義源文件路徑,使用name或dest來替換創建文件的符號鏈接。
下面我將web服務器中的fstab.bk文件屬主設為mysql,屬組設為mysql,權限設為666

[root@promote ~]# ansible web -m file -a ‘path=/opt/fstab.bk owner=mysql group=mysql mode=666‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "gid": 306, 
    "group": "mysql", 
    "mode": "0666", 
    "owner": "mysql", 
    "path": "/opt/fstab.bk", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 6, 
    "state": "file", 
    "uid": 306
}
[root@web ~]# ll /opt/fstab.bk 
-rw-rw-rw-. 1 mysql mysql 6 10月 22 23:10 /opt/fstab.bk

下面我為/opt/fstab.bk/創建一個鏈接文件

[root@promote ~]# ansible web -m file -a ‘src=/opt/fstab.bk path=/opt/fstab.bk.link state=link‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "dest": "/opt/fstab.bk.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:usr_t:s0", 
    "size": 13, 
    "src": "/opt/fstab.bk", 
    "state": "link", 
    "uid": 0
}
[root@web opt]# ll fstab.bk.link 
lrwxrwxrwx. 1 root root 13 10月 22 23:23 fstab.bk.link -> /opt/fstab.bk

7 ping 模塊
在ansible中使用ping模塊來檢測指定主機的連通性

[root@promote ~]# ansible all -m ping      
192.168.199.130 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.199.131 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

8 yum 模塊
ansible中的yum模塊負責在被管理主機上安裝與卸載軟件包,但是需要提前在每個節點配置自己的yum倉庫。其中name指定要安裝的軟件包,還需要帶上軟件包的版本號,否則安裝最新的軟件包,使用state指定安裝軟件包的狀態,present,latest用來表示安裝,absent表示卸載。

[root@promote ~]# ansible-doc -s yum
- name: Manages packages with the `yum‘ package manager
  yum:
      allow_downgrade:       # Specify if the named package and version is allowed
                               to downgrade a maybe
                               already installed
                               higher version of that
                               package.

在web服務器上安裝httpd服務:

[root@promote ~]# ansible web -m yum -a ‘name=httpd‘
192.168.199.130 | CHANGED => {
    "ansible_facts": {
        "pkg_mgr": "yum"
    }, 
    "changed": true, 
    "msg": "warning: /var/cache/yum/x86_64/7/base/packages/mailcap-2.1.41-2.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY\nhttp://mirrors.njupt.edu.cn/centos/7.5.1804/os/x86_64/Packages/apr-1.4.8-3.el7_4.1.x86_64.rpm: [Errno 14] HTTP Error 302 - Found\nTrying other mirror.\nImporting GPG key 0xF4A80EB5:\n Userid     : \"CentOS-7 Key (CentOS 7 Official Signing Key) <[email protected]>\"\n Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5\n Package    : centos-release-7-4.1708.el7.centos.x86_64 (@anaconda)\n From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7\n", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirrors.njupt.edu.cn\n * extras: mirrors.nju.edu.cn\n * updates: mirrors.njupt.edu.cn\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:\nPublic key for mailcap-2.1.41-2.el7.noarch.rpm is not installed\nPublic key for httpd-tools-2.4.6-80.el7.centos.1.x86_64.rpm is not installed\n--------------------------------------------------------------------------------\nTotal                                              143 kB/s | 3.0 MB  00:21     \nRetrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7\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"
    ]
}
[root@web ~]# rpm -q httpd                   #在web服務器上進行查看
httpd-2.4.6-80.el7.centos.1.x86_64

卸載的命令為ansible web -m yum -a ‘name=httpd state=absent‘ 這裏為了我下面的實驗就先不卸載了

9 service 模塊
在ansible模塊中使用service模塊來控制管理服務的運行狀態。其中,使用enabled表示是否開機自動啟動,取值為true或者false;使用name定義服務名稱;使用state指定服務狀態,取值分別為start,stopped,restarted.

下面我先查看web服務器上的httpd服務的運行狀態

[root@promote ~]# ansible web -a ‘systemctl status httpd.service‘
192.168.199.130 | FAILED | rc=3 >>             #可以看到現在httpd服務是關閉狀態
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)

接著我開啟web服務器上的httpd服務,並設為開機自啟動

[root@promote ~]# ansible web -m service -a ‘enabled=true name=httpd state=started‘
192.168.199.130 | SUCCESS => {
    "changed": false, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
[root@web ~]# systemctl status httpd.service              #到web服務器上查看狀態
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since 一 2018-10-22 23:47:51 CST; 2min 58s ago          #可以看到服務為運行狀態

最後我將web服務器的httpd服務進行關閉

[root@promote ~]# ansible web -m service -a ‘name=httpd enabled=true state=stopped‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "stopped", 
    "status": {
[root@web ~]# systemctl status httpd.service           #再次到web服務器進行查看
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since 一 2018-10-22 23:54:30 CST; 25s ago                        #可以看到httpd已經關閉

10 shell 模塊
ansible中的shell模塊可以在被管理主機上運行命令,並支持像管道符號等功能的復雜命令。

[root@promote ~]# ansible-doc -s shell
- name: Execute commands in nodes.
  shell:
      chdir:                 # cd into this directory before running the command
      creates:               # a filename, when it already exists, this step will
                               *not* be run.
      executable:            # change the shell used to execute the command. Should
                               be an absolute path to
                               the executable.
      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
                               examples!
      removes:               # a filename, when it does not exist, this step will
                               *not* be run.
      stdin:                 # Set the stdin of the command directly to the
                               specified value.
      warn:                  # if command warnings are on in ansible.cfg, do not
                               warn about this
                               particular line if set
                               to no/false.

下面我創建一個Jerry用戶,並為這個用戶設置密碼:

[root@promote ~]# ansible web -m user -a ‘name=jerry‘              #創建Jerry用戶
192.168.199.130 | CHANGED => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/jerry", 
    "name": "jerry", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}
[root@promote ~]# ansible web -m shell -a ‘echo 123456 | passwd --stdin jerry‘             #為用戶設置密碼為123456
192.168.199.130 | CHANGED | rc=0 >>
更改用戶 jerry 的密碼 。
passwd:所有的身份驗證令牌已經成功更新。

11 script 模塊
ansible中的script模塊可以將本地腳本復制到被管理主機上進行運行。需要註意的是,使用相對路徑來指定腳本。

[root@promote ~]# vim test.sh
#!/bin/bash
echo "this is test script" > /opt/script.txt
chmod 666 /opt/script.txt                         #寫一個腳本,表示在/opt/創建一個script.txt文件,權限設為666

[root@promote ~]# chmod +x test.sh
[root@promote ~]# ansible web -m script -a ‘test.sh‘
192.168.199.130 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.199.130 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.199.130 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
[root@web ~]# ls -l /opt/script.txt                    #到web服務器上進行查看
-rw-rw-rw-. 1 root root 20 10月 23 00:07 /opt/script.txt
[root@web ~]# cat /opt/script.txt 
this is test script

12 setup 模塊
在ansible中使用setup模塊收集,查看被管理主機的facts(faces是ansible采集被管理主機設備信息的一個功能)。每個被管理主機在接受並運行管理命令之前,都會將自己的相關信息發送給控制主機。

[root@promote ~]# ansible web -m setup          #對web服務器進行查看,顯示的信息非常多,這裏我只選了一部分
192.168.199.130 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.122.1", 
            "192.168.199.130"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::a392:f598:b619:50"
        ], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "05/19/2017", 
        "ansible_bios_version": "6.00", 
        "ansible_cmdline": {
            "BOOT_IMAGE": "/boot/vmlinuz-3.10.0-693.el7.x86_64", 
            "LANG": "zh_CN.UTF-8", 
            "crashkernel": "auto", 
            "quiet": true, 
            "rhgb": true, 
            "ro": true, 
            "root": "UUID=1eead85f-d0ea-464e-b163-f9c7475dbf65"
        }, 
...........

詳解Ansible服務常用命令模塊