Ansible常见模块及用法

Ansible常见模块及用法

一、ansible选项说明

[root@cen7 ~]# man ansible

ansible [options]

ansible [-f forks] [-m module_name] [-a args]

         -m module:没指定-m选项,默认为command

         -a MODULE_ARGS, --args MODULE_ARGS:模块参数,,如果执行默认COMMAND的模块,即是命令参数,如:“date”,"pwd"等等

         -f forks:并行任务数。NUM被指定为一个整数,默认是5

  -l SUBSET, --limit SUBSET:进一步限制所选主机/组模式  --limit=192.168.91.135 只对这个ip执行

         -S, --su:使用su命令

         -s, --sudo:使用sudo免密

         -B SECONDS, --background=SECONDS:后台运行超时时间

  -T TIMEOUT, --timeout=TIMEOUT:SSH超时时间,默认是10S

[root@cen7 ~]# ansible-doc -l

查询ansible支持的核心模块

[root@cen7 ~]# ansible-doc -h

Usage: ansible-doc [-l|-F|-s] [options] [-t ] [plugin]

plugin documentation tool

Options:

  -a, --all             **For internal testing only** Show documentation for

                        all plugins.

  -h, --help            show this help message and exit

  -l, --list            List available plugins

  -F, --list_files      Show plugin names and their source files without

                        summaries (implies --list)

  -M MODULE_PATH, --module-path=MODULE_PATH

                        prepend colon-separated path(s) to module library

                        (default=[u'/root/.ansible/plugins/modules',

                        u'/usr/share/ansible/plugins/modules'])

  -s, --snippet         Show playbook snippet for specified plugin(s)

  -t TYPE, --type=TYPE  Choose which plugin type (defaults to "module")

  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable

                        connection debugging)

  --version             show program's version number and exit

查询模块文档:

[root@cen7 ~]# ansible-doc -s modename

二、ansible常用模块及用法

1、命令模块(command)及常见错误说明

[root@cen7 ~]# ansible-doc -s command

在远程节点执行一个命令,command模块要执行的命令不用设置为key=value格式,直接给出要执行的命令即可,而且-m command可以省略

参数 :-a 'command'

[root@cen7 ~]# ansible 192.168.88.131 -m command -a 'date'

警告:提示没有主机匹配,所有主机都应该定义在主机清单当中

 [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit

localhost does not match 'all'

 [WARNING]: Could not match supplied host pattern, ignoring: 192.168.88.131

[root@cen7 ~]# cd /etc/ansible/

[root@cen7 ansible]# ls

ansible.cfg  hosts  roles

[root@cen7 ansible]# cp hosts{,.backup}

[root@cen7 ansible]# vi hosts

[root@cen7 ansible]# more hosts

192.168.88.132

[websrvs]

192.168.88.130

192.168.88.131

[dbsrvs]

192.168.88.130

192.168.88.129

例1、单一远程节点执行命令:直接指定远程节点IP

[root@cen7 ansible]# ansible 192.168.88.131 -m command -a 'ifconfig'

192.168.88.131 | SUCCESS | rc=0 >>

eth1      Link encap:Ethernet  HWaddr 00:0C:29:E3:90:19 

          inet addr:192.168.88.131  Bcast:192.168.88.255  Mask:255.255.255.0 …

例2、所有远程节点都执行命令:使用all参数

[root@cen7 ansible]# ansible all -m command -a 'date'

The authenticity of host '192.168.88.132 (192.168.88.132)' can't be established.

ECDSA key fingerprint is SHA256:lX5CsTbmnydhZUoUX49gGr02T8d79E8paqrc1FNUaAE.

ECDSA key fingerprint is MD5:d7:38:2c:fd:ed:89:f8:8b:a4:70:f6:bc:8f:19:63:03.

Are you sure you want to continue connecting (yes/no)? 192.168.88.129 | UNREACHABLE! => {

    "changed": false,

    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.88.129 port 22: No route to host\r\n",

    "unreachable": true

}

#此处报错No route to host,原因是129主机没有启动

192.168.88.131 | SUCCESS | rc=0 >>

2018年 06月 13日 星期三 15:04:40 CST

192.168.88.130 | SUCCESS | rc=0 >>

2018年 06月 13日 星期三 15:04:42 CST

192.168.88.132 | UNREACHABLE! => {

    "changed": false,

    "msg": "Failed to connect to the host via ssh: Host key verification failed.\r\n",

    "unreachable": true

}

#此处报错原因为192.168.88.132(本机)位配置ssh单向信任:

#注意:如果需要在本机上执行命令,则必须配置对本机的ssh单向信任

[root@cen7 ansible]# ssh-copy-id -i  ~/.ssh/id_rsa.pub [email protected]

 [root@cen7 ansible]# vi hosts

#192.168.88.129

[root@cen7 ansible]# ansible all -a 'date'

192.168.88.132 | SUCCESS | rc=0 >>

2018年 06月 13日 星期三 23:10:26 CST

192.168.88.130 | SUCCESS | rc=0 >>

2018年 06月 13日 星期三 15:10:30 CST

192.168.88.131 | SUCCESS | rc=0 >>

2018年 06月 13日 星期三 15:10:31 CST

例3、下载阿里yum源websrvs主机/field/tmp目录下

[root@cen7 ansible]# ansible websrvs -a 'wget -O /field/tmp/Centos-7.repo http://mirrors.aliyun.com/repo/Centos-7.repo'

 [WARNING]: Consider using the get_url or uri module rather than running wget.  If you need to use command because get_url or uri is insufficient you can add warn=False to this command task

or set command_warnings=False in ansible.cfg to get rid of this message.

#此处提示下载可以使用get_url模块

192.168.88.130 | SUCCESS | rc=0 >>

--2018-06-13 15:16:37--  http://mirrors.aliyun.com/repo/Centos-7.repo

正在解析主机 mirrors.aliyun.com... 121.31.31.39, 121.31.31.210, 121.31.31.40, ...

略…

     0K ..                                                    100%  222M=0s

2018-06-13 15:16:37 (222 MB/s) - 已保存 “/field/tmp/Centos-7.repo” [2573/2573])

[root@www ~]# ll /field/tmp/

总用量 4

-rw-r--r--. 1 root root 2573 11月 21 2014 Centos-7.repo

2user模块:用户模块

参用参数:

-a 'name=xxx state={present|absent} system={yes|no} uid=xxx'

其它参数:ansible-doc -s user

例1、创建普通用户

[root@cen7 ansible]# ansible websrvs -m user -a "name=hauser state=present"

192.168.88.130 | SUCCESS => {

    "changed": true,

    "comment": "",

    "create_home": true,

    "group": 502,

    "home": "/home/hauser",

    "name": "hauser",

    "shell": "/bin/bash",

    "state": "present",

    "system": false,

    "uid": 502

}

192.168.88.131 | SUCCESS => {

    "changed": true,

    "comment": "",

    "create_home": true,

    "group": 502,

    "home": "/home/hauser",

    "name": "hauser",

    "shell": "/bin/bash",

    "state": "present",

    "system": false,

    "uid": 502

}

[root@test tmp]# id hauser

uid=502(hauser) gid=502(hauser) 组=502(hauser)

例2、删除用户

[root@cen7 ansible]# ansible websrvs -m user -a "name=hauser state=absent"

192.168.88.130 | SUCCESS => {

    "changed": true,

    "force": false,

    "name": "hauser",

    "remove": false,

    "state": "absent"

}

192.168.88.131 | SUCCESS => {

}

[root@test tmp]# id hauser

id: hauser:无此用户

例3、创建系统用户

[root@cen7 ansible]# ansible websrvs -m user -a "name=hauser state=present system=yes"

192.168.88.130 | SUCCESS => {

    "changed": true,

    "comment": "",

    "create_home": true,

    "group": 491,

    "home": "/home/hauser",

    "name": "hauser",

    "shell": "/bin/bash",

    "state": "present",

    "stderr": "useradd:警告:此主目录已经存在。\n不从 skel 目录里向其中复制任何文件。\n",

    "stderr_lines": [

        "useradd:警告:此主目录已经存在。",

        "不从 skel 目录里向其中复制任何文件。"

    ],

    "system": true,

    "uid": 494

}

192.168.88.131 | SUCCESS => {

    "changed": true,

    "comment": "",

    "create_home": true,

    "group": 491,

    "home": "/home/hauser",

    "name": "hauser",

    "shell": "/bin/bash",

    "state": "present",

    "stderr": "useradd:警告:此主目录已经存在。\n不从 skel 目录里向其中复制任何文件。\n",

    "stderr_lines": [

        "useradd:警告:此主目录已经存在。",

        "不从 skel 目录里向其中复制任何文件。"

    ],

    "system": true,

    "uid": 494

}

3group模块:组模块

模块参数:

-a  'name=xxx gid=xxx state={present|absent} system={yes|no}'

其它参数:ansible-doc -s group

4、cron模块:定时任务

常见参数:

-a 'name= minute= hour= day= month= weekday= job= user= state={present|absent}'

minute/hour/day/month/weekday支持crontab定义方式

其它参数:ansible-doc -s cron

例1:创建定时任务每十分钟打印一次时间

[root@cen7 ansible]# ansible all -m cron -a 'name="date time now" minute="*/10" job="date  &>/dev/null"'

192.168.88.131 | SUCCESS => {

    "changed": true,

    "envs": [],

    "jobs": [

        "date time now"

    ]

}

192.168.88.132 | SUCCESS => {

    ]

}

192.168.88.130 | SUCCESS => {

..

    ]

}

[root@cen7 ansible]# crontab -l

#Ansible: date time now

*/10 * * * * date  &>/dev/null

例2:删除定时任务

[root@cen7 ansible]# ansible all -m cron -a 'name="date time now" state=absent'

192.168.88.130 | SUCCESS => {

    "changed": true,

    "envs": [],

    "jobs": []

}

192.168.88.131 | SUCCESS => {

    "changed": true,

    "envs": [],

    "jobs": []

}

192.168.88.132 | SUCCESS => {

    "changed": true,

    "envs": [],

    "jobs": []

}

[root@cen7 ansible]# crontab -l

5copy模块:文件复制

-a 'src=/path/src/xxx dest=/path/dest/xxx mode= owner= group= '

其它参数: ansible-doc -s copy

例:复制本机的/etc/fstab到dbsrvs主机中的/field/tmp/目录下并重命名fstab.tmp,权限600

[root@cen7 ansible]# ansible dbsrvs -m copy -a 'src=/etc/fstab dest=/field/tmp/fstab.tmp mode=600'

192.168.88.130 | SUCCESS => {

    "changed": true,

    "checksum": "8d9ab5a0ad52a259783fc5c49014423fa597e10c",

    "dest": "/field/tmp/fstab.tmp",

    "gid": 0,

    "group": "root",

    "md5sum": "a2a31120aeff68ba321311d2e7354073",

    "mode": "0600",

    "owner": "root",

    "size": 501,

    "src": "~None/.ansible/tmp/ansible-tmp-1528906608.29-210750219431524/source",

    "state": "file",

    "uid": 0

}

[root@test tmp]# ll /field/tmp/

总用量 8

-rw-r--r-- 1 root root 2573 11月 21 2014 Centos-7.repo

-rw------- 1 root root  501 6月  13 16:16 fstab.tmp

6file模块:设置文件属性

-a 'path= mode= owner= group= state= src= force='

state选项:

`directory`, 不存在则创建目录

`file`, 不存在不会创建

`link', 创建连接,源文件存在才创建

`absent`,删除文件

`present`,创建文件

`touch` :创建文件

其它参数:ansible-doc -s file

例1:创建目录/field/tmp/testdir

[root@cen7 ansible]# ansible all -m file -a 'path=/field/tmp/testdir state=directory'

192.168.88.130 | SUCCESS => {

    "changed": true,

    "gid": 0,

    "group": "root",

    "mode": "0755",

    "owner": "root",

    "path": "/field/tmp/testdir",

    "size": 4096,

    "state": "directory",

    "uid": 0

}

192.168.88.131 | SUCCESS => {

}

192.168.88.132 | SUCCESS => {

}

[root@cen7 ansible]# cd /field/tmp/

[root@cen7 tmp]# ll

总用量 0

drwxr-xr-x. 2 root root 6 6月  14 00:26 testdir

例2:创建链接

[root@cen7 tmp]# ansible all -m file -a 'path=/field/tmp/fstab.symlink state=link src=/field/tmp/fstab.tmp'

192.168.88.130 | SUCCESS => {

    "changed": true,

    "dest": "/field/tmp/fstab.symlink",

    "gid": 0,

    "group": "root",

    "mode": "0777",

    "owner": "root",

    "size": 20,

    "src": "/field/tmp/fstab.tmp",

    "state": "link",

    "uid": 0

}

192.168.88.132 | FAILED! => {

    "changed": false,

    "msg": "src file does not exist, use \"force=yes\" if you really want to create the link: /field/tmp/fstab.tmp",

    "path": "/field/tmp/fstab.symlink",

    "src": "/field/tmp/fstab.tmp",

    "state": "absent"

}

192.168.88.131 | FAILED! => {

    "changed": false,

    "msg": "src file does not exist, use \"force=yes\" if you really want to create the link: /field/tmp/fstab.tmp",

    "path": "/field/tmp/fstab.symlink",

    "src": "/field/tmp/fstab.tmp",

    "state": "absent"

}

[root@test tmp]# ll /field/tmp/

总用量 12

-rw-r--r-- 1 root root 2573 11月 21 2014 Centos-7.repo

lrwxrwxrwx 1 root root   20 6月  13 16:29 fstab.symlink -> /field/tmp/fstab.tmp

-rw------- 1 root root  501 6月  13 16:16 fstab.tmp

drwxr-xr-x 2 root root 4096 6月  13 16:26 testdir

例3:源文件不存在时强制创建链接

[root@cen7 tmp]# ansible all -m file -a 'path=/field/tmp/fstab.symlink state=link src=/field/tmp/fstab.tmp force=yes'

192.168.88.130 | SUCCESS => {

    "changed": false,

    "dest": "/field/tmp/fstab.symlink",

    "gid": 0,

    "group": "root",

    "mode": "0777",

    "owner": "root",

    "size": 20,

    "src": "/field/tmp/fstab.tmp",

    "state": "link",

    "uid": 0

}

 [WARNING]: Cannot set fs attributes on a non-existent symlink target. follow should be set

to False to avoid this.

192.168.88.132 | SUCCESS => {

    "changed": true,

    "dest": "/field/tmp/fstab.symlink",

    "src": "/field/tmp/fstab.tmp",

    "state": "absent"

}

192.168.88.131 | SUCCESS => {

    "changed": true,

    "dest": "/field/tmp/fstab.symlink",

    "src": "/field/tmp/fstab.tmp",

    "state": "absent"

}

[root@cen7 tmp]# ll /field/tmp/

总用量 0

lrwxrwxrwx. 1 root root 20 6月  14 00:31 fstab.symlink -> /field/tmp/fstab.tmp

drwxr-xr-x. 2 root root  6 6月  14 00:26 testdir:

例4:创建文件/field/tmp/fstab.tmp

[root@cen7 tmp]# ansible all -m file -a 'path=/field/tmp/fstab.tmp state=touch'

192.168.88.130 | SUCCESS => {

    "changed": true,

    "dest": "/field/tmp/fstab.tmp",

    "gid": 0,

    "group": "root",

    "mode": "0600",

    "owner": "root",

    "size": 501,

    "state": "file",

    "uid": 0

}

192.168.88.132 | SUCCESS => {

}

192.168.88.131 | SUCCESS => {

 …

}

[root@cen7 tmp]# ll /field/tmp/

总用量 0

lrwxrwxrwx. 1 root root 20 6月  14 00:31 fstab.symlink -> /field/tmp/fstab.tmp

-rw-r--r--. 1 root root  0 6月  14 00:33 fstab.tmp

drwxr-xr-x. 2 root root  6 6月  14 00:26 testdir

例5:删除文件

[root@cen7 tmp]# ansible all -m file -a 'path=/field/tmp/fstab.symlink state=absent force=yes'

192.168.88.130 | SUCCESS => {

    "changed": true,

    "path": "/field/tmp/fstab.symlink",

    "state": "absent"

}

192.168.88.131 | SUCCESS => {

}

192.168.88.132 | SUCCESS => {

}

[root@cen7 tmp]# ll /field/tmp/

总用量 0

-rw-r--r--. 1 root root 0 6月  14 00:33 fstab.tmp

drwxr-xr-x. 2 root root 6 6月  14 00:26 testdir

7ping模块:没有参数,返回pong成功

[root@cen7 tmp]# ansible-doc -s ping

- name: Try to connect to host, verify a usable python and return `pong' on success

  ping:

      data:   # Data to return for the `ping' return value. If this parameter is set to `crash', the module will cause an exception.

[root@cen7 tmp]# ansible all -m ping

192.168.88.130 | SUCCESS => {

    "changed": false,

    "ping": "pong"

}

192.168.88.131 | SUCCESS => {

    "changed": false,

    "ping": "pong"

}

192.168.88.132 | SUCCESS => {

    "changed": false,

    "ping": "pong"

}

8、yum模块:安装模块

-a 'name= state= '

state选项:

安装选项 (`present' or `installed', `latest')

卸载选项(`absent' or `removed')

其它参数:ansible-doc -s yum

例:yum安装最新版Nginx

[root@cen7 tmp]# ansible all -m yum -a 'name=nginx state=latest'

192.168.88.130 | SUCCESS => {

    "changed": false,

    "msg": "",

    "rc": 0,

    "results": [

        "All packages providing nginx are up to date",

        ""

    ]

}

192.168.88.132 | SUCCESS => {

    "changed": true,

    "msg": "…

    "rc": 0,

    "results": [

...    ]

}

192.168.88.131 | SUCCESS => {

    "changed": false,

    "msg": "",

    "rc": 0,

    "results": [

        "All packages providing nginx are up to date",

        ""

    ]

}

[root@cen7 tmp]# rpm -q nginx

nginx-1.12.2-2.el7.x86_64

9sevice模块:服务管理模块

-a 'name= state= enabled= '

enabled:是否开机自启

name:服务器名

state: `started'、`stopped'、 `restarted'、 `reloaded'

其它参数:ansible-doc -s service

例1:启动所有主机的Nginx服务并配置开机自启动

[root@cen7 tmp]# ansible all -m service -a 'name=nginx state=started enabled=yes'

192.168.88.132 | SUCCESS => {

    "changed": false,

    "enabled": true,

    "name": "nginx",

    "state": "started",

}

192.168.88.130 | SUCCESS => {

    "changed": true,

    "enabled": true,

    "name": "nginx",

    "state": "started"

}

192.168.88.131 | SUCCESS => {

}

[root@www ~]#  chkconfig --list nginx

nginx              0:关闭      1:关闭      2:启用      3:启用      4:启用      5:启用      6:关闭

例2:关闭所有主机的Nginx服务并关闭开机自启动

[root@cen7 tmp]# ansible all -m service -a 'name=nginx state=stopped enabled=no'

192.168.88.132 | SUCCESS => {

    "changed": true,

    "enabled": false,

    "name": "nginx",

    "state": "stopped",

}

192.168.88.130 | SUCCESS => {

}

192.168.88.131 | SUCCESS => {

}

[root@www ~]#  chkconfig --list nginx

nginx              0:关闭      1:关闭      2:关闭      3:关闭      4:关闭      5:关闭      6:关闭

[root@www ~]# service nginx status

nginx 已停

10shell模块:运行shell命令的模块

command模块模块无法实现的命令可以在该模块中实现

-a 'command'

其它参数: ansible-doc -s shell

例1:command模块无法创建密码

[root@cen7 tmp]# ansible all -m user -a 'name=centos state=present'

 [root@cen7 tmp]# ansible all -m command -a 'echo centos | passwd --stdin centos'

192.168.88.132 | SUCCESS | rc=0 >>

centos | passwd --stdin centos

192.168.88.130 | SUCCESS | rc=0 >>

centos | passwd --stdin centos

192.168.88.131 | SUCCESS | rc=0 >>

centos | passwd --stdin centos

例2:使用shell模块为centos设置密码centos

[root@cen7 tmp]# ansible all -m shell -a 'echo centos | passwd --stdin centos'

192.168.88.132 | SUCCESS | rc=0 >>

更改用户 centos 的密码 。

passwd:所有的身份验证令牌已经成功更新。:

192.168.88.130 | SUCCESS | rc=0 >>

更改用户 centos 的密码 。

passwd: 所有的身份验证令牌已经成功更新。

192.168.88.131 | SUCCESS | rc=0 >>

更改用户 centos 的密码 。

passwd: 所有的身份验证令牌已经成功更新。

11script模块:脚本模块,运行脚本

-a  '/path/to/script'

其它参数:ansible-doc -s script

示例:编辑脚本,打印$(hostname) :hello ansible!到/field/tmp/ansible.txt文件中

[root@cen7 tmp]# vi test.sh

[root@cen7 tmp]# more test.sh

#!/bin/bash

#

echo "$(hostname) :hello ansible!" >/field/tmp/ansible.txt

[root@cen7 tmp]# pwd

/field/tmp

[root@cen7 tmp]# ansible all -m script -a '/field/tmp/test.sh'

192.168.88.130 | SUCCESS => {

    "changed": true,

    "rc": 0,

    "stderr": "Shared connection to 192.168.88.130 closed.\r\n",

    "stdout": "",

    "stdout_lines": []

}

192.168.88.132 | SUCCESS => {

}

192.168.88.131 | SUCCESS => {

}

[root@cen7 tmp]# cat /field/tmp/ansible.txt

cen7.field.com :hello ansible!

[root@www ~]# cat /field/tmp/ansible.txt

www.field.com :hello ansible!

12get_url模块:下载url文件到远程节点

示例:下载http://192.168.88.188web主页到hacluster主机的/tmp/

[root@cen7 corosync]# ansible hacluster -m get_url -a 'url=http://192.168.88.188 dest=/tmp/ '

192.168.88.133 | SUCCESS => {

    "changed": true,

    "checksum_dest": null,

    "checksum_src": "3c933cea3bf31cdd21df434583a1b963a5645195",

    "dest": "/tmp/index.html",

    "gid": 0,

    "group": "root",

    "md5sum": "ecd4084d153cfc71b21270e7da88a6b3",

    "mode": "0644",

    "msg": "OK (39 bytes)",

    "owner": "root",

    "size": 39,

    "src": "/tmp/tmpM4b1D5",

    "state": "file",

    "status_code": 200,

    "uid": 0,

    "url": "http://192.168.88.188"

}

192.168.88.134 | SUCCESS => {

    "changed": true,

    "checksum_dest": null,

    "checksum_src": "3c933cea3bf31cdd21df434583a1b963a5645195",

    "dest": "/tmp/index.html",

    "gid": 0,

    "group": "root",

    "md5sum": "ecd4084d153cfc71b21270e7da88a6b3",

    "mode": "0644",

    "msg": "OK (39 bytes)",

    "owner": "root",

    "size": 39,

    "src": "/tmp/tmp6LhfJW",

    "state": "file",

    "status_code": 200,

    "uid": 0,

    "url": "http://192.168.88.188"

}

192.168.88.132 | SUCCESS => {

    "changed": true,

    "checksum_dest": null,

    "checksum_src": "3c933cea3bf31cdd21df434583a1b963a5645195",

    "dest": "/tmp/index.html",

    "gid": 0,

    "group": "root",

    "md5sum": "ecd4084d153cfc71b21270e7da88a6b3",

    "mode": "0644",

    "msg": "OK (39 bytes)",

    "owner": "root",

    "size": 39,

    "src": "/tmp/tmpQw6qxk",

    "state": "file",

    "status_code": 200,

    "uid": 0,

    "url": "http://192.168.88.188"

}

13、setup模块:获取配置信息模块

[root@cen7 tmp]# ansible-doc -s setup

- name: Gathers facts about remote hosts

[root@cen7 tmp]# ansible dbsrvs -m setup

192.168.88.130 | SUCCESS => {

    "ansible_facts": {

        "ansible_all_ipv4_addresses": [

            "192.168.88.130"

        ],

        "ansible_all_ipv6_addresses": [

            "fe80::20c:29ff:fe4c:4cc"

        ],

        "ansible_apparmor": {

            "status": "disabled"

        },

        "ansible_architecture": "x86_64",

        "ansible_bios_date": "07/31/2013",

        "ansible_bios_version": "6.00",

        ...

        ...

        "gather_subset": [

            "all"

        ],

        "module_setup": true

    },

    "changed": false

}

       

 

你可能感兴趣的:(自动化运维工具,ansible常见模块,ansible用法,ansible自动化运维工具)