详解Ansible服务常用命令模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了详解Ansible服务常用命令模块相关的知识,希望对你有一定的参考价值。

ansible可以使用命令行方式进行自动化管理,基本语法如下:

ansible 主机名 -m 模块名称 -a 模块特有参数

ansible的命令行管理工具都是由一系列模块、参数所支持的,可以在命令后面加上-h或--help获取帮助。如使用ansible-doc -h或者ansible-doc --help查看其帮助信息
ansible-doc是用来查看模块帮助信息的工具,最主要的选项 -l用来列出可使用的模块, -s用来列出某个模块的描述信息和使用示例。

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

[[email protected] ~]# 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选项省略时会运行次模块,用于在被管理主机上运行命令

[[email protected] ~]# 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’命令来查看被管理主机的时间:

[[email protected] ~]# 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表示移除

[[email protected] ~]# 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.
......

添加任务计划:

[[email protected] ~]# 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"
    ]
}
[[email protected] ~]# ansible web -a ‘crontab -l‘            #查看web主机的计划性任务
192.168.199.130 | CHANGED | rc=0 >>
#Ansible: test hehe
*/1 * * * * /usr/bin/echo hehe

移除任务计划:

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

3 user模块
ansible中的user模块用于创建新用户和更改,删除已存在的用户,其中name项用来指明创建的用户名称
user模块是请求的是useadd,userdel,usermod三个指令

创建一个名为test01的用户:

[[email protected] ~]# 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用户:

[[email protected] ~]# 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三个指令

[[email protected] ~]# 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组中

[[email protected] ~]# 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
}
[[email protected] ~]# 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则是通过指定信息内容生成目标文件。

[[email protected] ~]# 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

[[email protected] ~]# 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
}
[[email protected] ~]# ll /opt/fstab.bk 
-rw-r--r--. 1 root root 595 10月 22 23:06 /opt/fstab.bk

接着我将"hello"写入“/opt/fstab.bk”

[[email protected] ~]# 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
}
[[email protected] ~]# cat /opt/fstab.bk 
hello!

6 file 模块
在ansible中使用file模块来设置文件属性。其中使用path指定文件路径,使用src定义源文件路径,使用name或dest来替换创建文件的符号链接。
下面我将web服务器中的fstab.bk文件属主设为mysql,属组设为mysql,权限设为666

[[email protected] ~]# 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
}
[[email protected] ~]# ll /opt/fstab.bk 
-rw-rw-rw-. 1 mysql mysql 6 10月 22 23:10 /opt/fstab.bk

下面我为/opt/fstab.bk/创建一个链接文件

[[email protected] ~]# 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
}
[[email protected] opt]# ll fstab.bk.link 
lrwxrwxrwx. 1 root root 13 10月 22 23:23 fstab.bk.link -> /opt/fstab.bk

7 ping 模块
在ansible中使用ping模块来检测指定主机的连通性

[[email protected] ~]# 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表示卸载。

[[email protected] ~]# 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服务:

[[email protected] ~]# 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
http://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
Trying other mirror.
Importing GPG key 0xF4A80EB5:
 Userid     : "CentOS-7 Key (CentOS 7 Official Signing Key) <[email protected]>"
 Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5
 Package    : centos-release-7-4.1708.el7.centos.x86_64 (@anaconda)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.njupt.edu.cn
 * extras: mirrors.nju.edu.cn
 * updates: mirrors.njupt.edu.cn
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:
Public key for mailcap-2.1.41-2.el7.noarch.rpm is not installed
Public key for httpd-tools-2.4.6-80.el7.centos.1.x86_64.rpm is not installed
--------------------------------------------------------------------------------
Total                                              143 kB/s | 3.0 MB  00:21     
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
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!
"
    ]
}
[[email protected] ~]# 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服务的运行状态

[[email protected] ~]# 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服务,并设为开机自启动

[[email protected] ~]# 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": {
[[email protected] ~]# 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服务进行关闭

[[email protected] ~]# 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": {
[[email protected] ~]# 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模块可以在被管理主机上运行命令,并支持像管道符号等功能的复杂命令。

[[email protected] ~]# 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用户,并为这个用户设置密码:

[[email protected] ~]# 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
}
[[email protected] ~]# ansible web -m shell -a ‘echo 123456 | passwd --stdin jerry‘             #为用户设置密码为123456
192.168.199.130 | CHANGED | rc=0 >>
更改用户 jerry 的密码 。
passwd:所有的身份验证令牌已经成功更新。

11 script 模块
ansible中的script模块可以将本地脚本复制到被管理主机上进行运行。需要注意的是,使用相对路径来指定脚本。

[[email protected] ~]# vim test.sh
#!/bin/bash
echo "this is test script" > /opt/script.txt
chmod 666 /opt/script.txt                         #写一个脚本,表示在/opt/创建一个script.txt文件,权限设为666

[[email protected] ~]# chmod +x test.sh
[[email protected] ~]# 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.
", 
    "stderr_lines": [
        "Shared connection to 192.168.199.130 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
[[email protected] ~]# ls -l /opt/script.txt                    #到web服务器上进行查看
-rw-rw-rw-. 1 root root 20 10月 23 00:07 /opt/script.txt
[[email protected] ~]# cat /opt/script.txt 
this is test script

12 setup 模块
在ansible中使用setup模块收集,查看被管理主机的facts(faces是ansible采集被管理主机设备信息的一个功能)。每个被管理主机在接受并运行管理命令之前,都会将自己的相关信息发送给控制主机。

[[email protected] ~]# 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服务常用命令模块的主要内容,如果未能解决你的问题,请参考以下文章

Ansible安装部署及常用模块详解

ansible常用模块详解

Ansible 常用模块详解

ansible自动化运维详解ansible管理方式常用参数及常用模块

ansible自动化运维详解ansible管理方式常用参数及常用模块

ansible自动化运维详解ansible管理方式常用参数及常用模块