ansible从入门到实践(一)

Ansible playbook 简介

ansible 是什么?
ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。
ansible是基于 paramiko 开发的,并且基于模块化工作,本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架。ansible不需要在远程主机上安装client/agents,因为它们是基于ssh来和远程主机通讯的。ansible目前已经已经被红帽官方收购,是自动化运维工具中大家认可度最高的,并且上手容易,学习简单。是每位运维工程师必须掌握的技能之一。
ansible 特点?
1.部署简单,只需在主控端部署Ansible环境,被控端无需做任何操作;
2.默认使用SSH协议对设备进行管理;
3.有大量常规运维操作模块,可实现日常绝大部分操作;
4.配置简单、功能强大、扩展性强;
5.支持API及自定义模块,可通过Python轻松扩展;
6.通过Playbooks来定制强大的配置、状态管理;
7.轻量级,无需在客户端安装agent,更新时,只需在操作机上进行一次更新即可;
8提供一个功能强大、操作性强的Web管理界面和REST API接口——AWX平台。
ansible 架构图
ansible从入门到实践(一)_第1张图片
1.sible:Ansible核心程序。
2.HostInventory:记录由Ansible管理的主机信息,包括端口、密码、ip等。
3.Playbooks:“剧本”YAML格式文件,多个任务定义在一个文件中,定义主机需要调用哪些模块来完成的功能。
4.CoreModules:核心模块,主要操作是通过调用核心模块来完成管理任务。
5.CustomModules:自定义模块,完成核心模块无法完成的功能,支持多种语言。
6.ConnectionPlugins:连接插件,Ansible和Host通信使用

ansible 任务执行

ansible 任务执行模式
  Ansible 系统由控制主机对被管节点的操作方式可分为两类,即adhoc和playbook:

1.ad-hoc模式(点对点模式)
  使用单个模块,支持批量执行单条命令。ad-hoc 命令是一种可以快速输入的命令,而且不需要保存起来的命令。就相当于bash中的一句话shell。
2.playbook模式(剧本模式)
  是Ansible主要管理方式,也是Ansible功能强大的关键所在。playbook通过多个task集合完成一类功能,如Web服务的安装部署、数据库服务器的批量备份等。可以简单地把playbook理解为通过组合多条ad-hoc操作的配置文件。

ansible 命令执行过程
1.加载自己的配置文件,默认/etc/ansible/ansible.cfg;
2.查找对应的主机配置文件,找到要执行的主机或者组;
3.加载自己对应的模块文件,如 command;
4.通过ansible将模块或命令生成对应的临时py文件(python脚本), 并将该文件传输至远程服务器;
5.对应执行用户的家目录的.ansible/tmp/XXX/XXX.PY文件;
6.给文件 +x 执行权限;
7.执行并返回结果;
8.删除临时py文件,sleep 0退出;

ansible 配置详解

一.准备环境
4台cenos7.4 的机器
分别为:

192.168.137.130 node.cwf.com node
192.168.137.131 node1.cwf.com node1
192.168.137.132 node2.cwf.com node2
192.168.137.133 node3.cwf.com node3

二.安装
使用 yum 安装
yum 安装是我们很熟悉的安装方式了。我们需要先安装一个epel-release包,然后再安装我们的 ansible 即可。

yum install epel-release -y
yum install ansible –y

ansible 程序结构

   配置文件目录:/etc/ansible/
  执行文件目录:/usr/bin/
  Lib库依赖目录:/usr/lib/pythonX.X/site-packages/ansible/
  Help文档目录:/usr/share/doc/ansible-X.X.X/
  Man文档目录:/usr/share/man/man1/

ansible配置文件

ansible 的配置文件为/etc/ansible/ansible.cfg,ansible 有许多参数,下面我们列出一些常见的参数:

    inventory = /etc/ansible/hosts      #这个参数表示资源清单inventory文件的位置
    library = /usr/share/ansible        #指向存放Ansible模块的目录,支持多个目录方式,只要用冒号(:)隔开就可以
    forks = 5       #并发连接数,默认为5
    sudo_user = root        #设置默认执行命令的用户
    remote_port = 22        #指定连接被管节点的管理端口,默认为22端口,建议修改,能够更加安全
    host_key_checking = False       #设置是否检查SSH主机的密钥,值为True/False。关闭后第一次连接不会提示配置实例
    timeout = 60        #设置SSH连接的超时时间,单位为秒
    log_path = /var/log/ansible.log     #指定一个存储ansible日志的文件(默认不记录日志)

ansible主机清单
1、 直接指明主机地址或主机名:
## green.example.com#
# blue.example.com#
# 192.168.100.1
# 192.168.100.10
2、 定义一个主机组[组名]把地址或主机名加进去
[mysql_test]
192.168.253.159
192.168.253.160
192.168.253.153

实例:


[web]
node1
node2
node3

三.ansible 常用命令
ansible [-f forks] [-m module_name] [-a args]

-a MODULE_ARGS   #模块的参数,如果执行默认COMMAND的模块,即是命令参数,如: “date”,“pwd”等等
-k,--ask-pass #ask for SSH password。登录密码,提示输入SSH密码而不是假设基于密钥的验证
--ask-su-pass #ask for su password。su切换密码
-K,--ask-sudo-pass #ask for sudo password。提示密码使用sudo,sudo表示提权操作
--ask-vault-pass #ask for vault password。假设我们设定了加密的密码,则用该选项进行访问
-B SECONDS #后台运行超时时间
-C #模拟运行环境并进行预运行,可以进行查错测试
-c CONNECTION #连接类型使用
-f FORKS #并行任务数,默认为5
-i INVENTORY #指定主机清单的路径,默认为/etc/ansible/hosts
--list-hosts #查看有哪些主机组
-m MODULE_NAME #执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
-o #压缩输出,尝试将所有结果在一行输出,一般针对收集工具使用
-S #用 su 命令
-R SU_USER #指定 su 的用户,默认为 root 用户
-s #用 sudo 命令
-U SUDO_USER #指定 sudo 到哪个用户,默认为 root 用户
-T TIMEOUT #指定 ssh 默认超时时间,默认为10s,也可在配置文件中修改
-u REMOTE_USER #远程用户,默认为 root 用户
-v #查看详细信息,同时支持-vvv,-vvvv可查看更详细信息

四.ansible 配置公私钥

上面我们已经提到过 ansible 是基于 ssh 协议实现的,所以其配置公私钥的方式与 ssh 协议的方式相同,具体操作步骤如下:

#1.生成私钥

[root@node ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:h9ujbcfPHqUPWQ38qtPV/DuuYJbRUi/XYYv3zcZbGLc root@node
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|             .   |
|             .oo |
|         .  o +o=|
|        S .o +.*O|
|         +  + +%B|
|        . o* .BEO|
|         o+.=o.*+|
|        .....=*++|
+----[SHA256]-----+

#2.向主机分发私钥

[root@node ~]# ssh-copy-id root@node1
[root@node ~]# ssh-copy-id root@node2
[root@node ~]# ssh-copy-id root@node3

ansible 常用模块

1)主机连通性测试
  我们使用ansible web -m ping命令来进行主机连通性测试,效果如下:

[root@node ~]# ansible web -m ping
node3 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
node2 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
node1 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

这样就说明我们的主机是连通状态的。接下来的操作才可以正常进行。

2)command 模块
  这个模块可以直接在远程主机上执行命令,并将结果返回本主机。
  举例如下:

[root@node ~]# ansible web -m command -a "ip a"
node3 | CHANGED | rc=0 >>
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens33:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:5a:db:9f brd ff:ff:ff:ff:ff:ff
    inet 192.168.137.133/24 brd 192.168.137.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::7e86:5ee3:1708:2a3/64 scope link tentative dadfailed
       valid_lft forever preferred_lft forever
    inet6 fe80::8b47:ff57:3278:b565/64 scope link tentative dadfailed
       valid_lft forever preferred_lft forever
    inet6 fe80::1b2:ee8f:644e:fb16/64 scope link tentative dadfailed
       valid_lft forever preferred_lft forever

node2 | CHANGED | rc=0 >>
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens33:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:d9:b9:ce brd ff:ff:ff:ff:ff:ff
    inet 192.168.137.132/24 brd 192.168.137.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::8b47:ff57:3278:b565/64 scope link
       valid_lft forever preferred_lft forever
    inet6 fe80::1b2:ee8f:644e:fb16/64 scope link tentative dadfailed
       valid_lft forever preferred_lft forever

node1 | CHANGED | rc=0 >>
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens33:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:96:13:37 brd ff:ff:ff:ff:ff:ff
    inet 192.168.137.131/24 brd 192.168.137.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::1b2:ee8f:644e:fb16/64 scope link
       valid_lft forever preferred_lft forever


命令模块接受命令名称,后面是空格分隔的列表参数。给定的命令将在所有选定的节点上执行。它不会通过shell进行处理,比如$HOME和操作如"<",">","|",";","&" 工作(需要使用(shell)模块实现这些功能)。注意,该命令不支持| 管道命令。
  下面来看一看该模块下常用的几个命令:

chdir # 在执行命令之前,先切换到该目录
executable # 切换shell来执行命令,需要使用命令的绝对路径
free_form # 要执行的Linux指令,一般使用Ansible的-a参数代替。
creates # 一个文件名,当这个文件存在,则该命令不执行,可以用来做判断
removes # 一个文件名,这个文件不存在,则该命令不执行

下面我们来看看这些命令的执行效果:



[root@node ~]# ansible web -m command -a "chdir=/root/ ls"
node2 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

node1 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

node3 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

[root@node ~]# ansible web -m command -a 'creates=/root/test ls'
node3 | SUCCESS | rc=0 >>
skipped, since /root/test exists

node2 | SUCCESS | rc=0 >>
skipped, since /root/test exists

node1 | SUCCESS | rc=0 >>
skipped, since /root/test exists

[root@node ~]# ansible web -m command -a 'creates=/root/testa ls'
node2 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

node1 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

node3 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

[root@node ~]# ansible web -m command -a 'removes=/root/test ls'
node1 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

node3 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

node2 | CHANGED | rc=0 >>
anaconda-ks.cfg
test

3)shell 模块
  shell模块可以在远程主机上调用shell解释器运行命令,支持shell的各种功能,例如管道等。
  说明: shell 模块在远程执行脚本时,远程主机上一定要有相应的脚本


[root@node ~]# ansible web -m shell -a 'cat /etc/passwd | grep root'
node2 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

node1 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

node3 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

只要是我们的shell命令,都可以通过这个模块在远程主机上运行,这里就不一一举例了。

4)copy 模块
  这个模块用于将文件复制到远程主机,同时支持给定内容生成文件和修改权限等。
  其相关选项如下:

src #被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"
content #用于替换"src",可以直接指定文件的值
dest #必选项,将源文件复制到的远程主机的绝对路径
backup #当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息
directory_mode #递归设定目录的权限,默认为系统默认权限
force #当目标主机包含该文件,但内容不同时,设为"yes",表示强制覆盖;设为"no",表示目标主机的目标位置不存在该文件才复制。默认为"yes"
others #所有的 file 模块中的选项可以在这里使用

用法举例如下:
① 复制文件:

[root@node ~]# ansible web -m copy -a "src=~/anaconda-ks.cfg dest=/"
node1 | CHANGED => {
    "changed": true,
    "checksum": "07803aeac53d28b2ead1f7ed25f21cbd2f4088e9",
    "dest": "/anaconda-ks.cfg",
    "gid": 0,
    "group": "root",
    "md5sum": "6624b891b51e3697b3211f4524e97737",
    "mode": "0644",
    "owner": "root",
    "size": 1408,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089421.46-217830054553967/source",
    "state": "file",
    "uid": 0
}
node3 | CHANGED => {
    "changed": true,
    "checksum": "07803aeac53d28b2ead1f7ed25f21cbd2f4088e9",
    "dest": "/anaconda-ks.cfg",
    "gid": 0,
    "group": "root",
    "md5sum": "6624b891b51e3697b3211f4524e97737",
    "mode": "0644",
    "owner": "root",
    "size": 1408,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089421.5-161964763288871/source",
    "state": "file",
    "uid": 0
}
node2 | CHANGED => {
    "changed": true,
    "checksum": "07803aeac53d28b2ead1f7ed25f21cbd2f4088e9",
    "dest": "/anaconda-ks.cfg",
    "gid": 0,
    "group": "root",
    "md5sum": "6624b891b51e3697b3211f4524e97737",
    "mode": "0644",
    "owner": "root",
    "size": 1408,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089421.48-212384123379480/source",
    "state": "file",
    "uid": 0
}

② 给定内容生成文件,并制定权限

[root@node ~]# ansible web -m copy -a 'content="I am keer\n" dest=/test mode=666'
node2 | CHANGED => {
    "changed": true,
    "checksum": "0421570938940ea784f9d8598dab87f07685b968",
    "dest": "/test",
    "gid": 0,
    "group": "root",
    "md5sum": "497fa8386590a5fc89090725b07f175c",
    "mode": "0666",
    "owner": "root",
    "size": 10,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089520.53-226397712632608/source",
    "state": "file",
    "uid": 0
}
node3 | CHANGED => {
    "changed": true,
    "checksum": "0421570938940ea784f9d8598dab87f07685b968",
    "dest": "/test",
    "gid": 0,
    "group": "root",
    "md5sum": "497fa8386590a5fc89090725b07f175c",
    "mode": "0666",
    "owner": "root",
    "size": 10,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089520.54-252438891518875/source",
    "state": "file",
    "uid": 0
}
node1 | CHANGED => {
    "changed": true,
    "checksum": "0421570938940ea784f9d8598dab87f07685b968",
    "dest": "/test",
    "gid": 0,
    "group": "root",
    "md5sum": "497fa8386590a5fc89090725b07f175c",
    "mode": "0666",
    "owner": "root",
    "size": 10,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089520.51-122180181711221/source",
    "state": "file",
    "uid": 0
}

我们现在可以去查看一下我们生成的文件及其权限:

[root@node ~]# ansible web -m shell -a "ls -l /test"
node2 | CHANGED | rc=0 >>
-rw-rw-rw- 1 root root 10 Mar 31 23:32 /test

node1 | CHANGED | rc=0 >>
-rw-rw-rw- 1 root root 10 Mar 31 23:32 /test

node3 | CHANGED | rc=0 >>
-rw-rw-rw- 1 root root 10 Mar 31 23:32 /test

可以看出我们的name文件已经生成,并且权限为666。
③ 关于覆盖
  我们把文件的内容修改一下,然后选择覆盖备份:

 ansible web -m copy -a 'content="I am keerya\n" backup=yes dest=/test mode=666'
node1 | CHANGED => {
    "backup_file": "/test.9763.2019-03-31@23:34:27~",
    "changed": true,
    "checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "dest": "/test",
    "gid": 0,
    "group": "root",
    "md5sum": "8ca7c11385856155af52e560f608891c",
    "mode": "0666",
    "owner": "root",
    "size": 12,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089666.35-70993489630022/source",
    "state": "file",
    "uid": 0
}
node3 | CHANGED => {
    "backup_file": "/test.9829.2019-03-31@23:34:27~",
    "changed": true,
    "checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "dest": "/test",
    "gid": 0,
    "group": "root",
    "md5sum": "8ca7c11385856155af52e560f608891c",
    "mode": "0666",
    "owner": "root",
    "size": 12,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089666.36-329278362629/source",
    "state": "file",
    "uid": 0
}
node2 | CHANGED => {
    "backup_file": "/test.9732.2019-03-31@23:34:27~",
    "changed": true,
    "checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "dest": "/test",
    "gid": 0,
    "group": "root",
    "md5sum": "8ca7c11385856155af52e560f608891c",
    "mode": "0666",
    "owner": "root",
    "size": 12,
    "src": "/root/.ansible/tmp/ansible-tmp-1554089666.36-237341764097493/source",
    "state": "file",
    "uid": 0
}

5)file 模块
该模块主要用于设置文件的属性,比如创建文件、创建链接文件、删除文件等。
下面是一些常见的命令:

force #需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes no
group #定义文件/目录的属组。后面可以加上mode:定义文件/目录的权限
owner #定义文件/目录的属主。后面必须跟上path:定义文件/目录的路径
recurse #递归设置文件的属性,只对目录有效,后面跟上src:被链接的源文件路径,只应用于state=link的情况
dest #被链接到的路径,只应用于state=link的情况
state #状态,有以下选项:

directory:如果目录不存在,就创建目录
1.file:即使文件不存在,也不会被创建
2.link:创建软链接
3.hard:创建硬链接
4.touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
5.absent:删除目录、文件或者取消链接文件

用法举例如下:
① 创建目录:

[root@node ~]# ansible web -m file -a 'path=/data/app state=directory'
node3 | CHANGED => {
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/data/app",
    "size": 6,
    "state": "directory",
    "uid": 0
}
node2 | CHANGED => {
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/data/app",
    "size": 6,
    "state": "directory",
    "uid": 0
}
node1 | CHANGED => {
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/data/app",
    "size": 6,
    "state": "directory",
    "uid": 0
}

我们可以查看一下:

[root@node ~]#  ansible web -m shell -a 'ls -l /data'
node3 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 Mar 31 23:41 app

node2 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 Mar 31 23:41 app

node1 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 Mar 31 23:41 app

可以看出,我们的目录已经创建完成。
② 创建链接文件

[root@node ~]# ansible web -m file -a 'path=/data/bbb src=/data/app state=link'
node1 | CHANGED => {
    "changed": true,
    "dest": "/data/bbb",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "size": 9,
    "src": "/data/app",
    "state": "link",
    "uid": 0
}
node2 | CHANGED => {
    "changed": true,
    "dest": "/data/bbb",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "size": 9,
    "src": "/data/app",
    "state": "link",
    "uid": 0
}
node3 | CHANGED => {
    "changed": true,
    "dest": "/data/bbb",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "size": 9,
    "src": "/data/app",
    "state": "link",
    "uid": 0
}

我们可以去查看一下:

[root@node ~]# ansible web -m shell -a 'ls -l /data'
node3 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 Mar 31 23:41 app
lrwxrwxrwx 1 root root 9 Mar 31 23:46 bbb -> /data/app

node1 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 Mar 31 23:41 app
lrwxrwxrwx 1 root root 9 Mar 31 23:46 bbb -> /data/app

node2 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 Mar 31 23:41 app
lrwxrwxrwx 1 root root 9 Mar 31 23:46 bbb -> /data/app

我们的链接文件已经创建成功。
③ 删除文件

[root@node ~]# ansible web -m file -a 'path=/data/bbb state=absent'
node2 | CHANGED => {
    "changed": true,
    "path": "/data/bbb",
    "state": "absent"
}
node1 | CHANGED => {
    "changed": true,
    "path": "/data/bbb",
    "state": "absent"
}
node3 | CHANGED => {
    "changed": true,
    "path": "/data/bbb",
    "state": "absent"
}

我们可以查看一下:

[root@node ~]#  ansible web -m shell -a 'ls /data/'
node3 | CHANGED | rc=0 >>
app

node2 | CHANGED | rc=0 >>
app

node1 | CHANGED | rc=0 >>
app

发现已经没有这个文件了。

6)fetch 模块
  该模块用于从远程某主机获取(复制)文件到本地。
  有两个选项:

dest: 用来存放文件的目录
src: 在远程拉取的文件,并且必须是一个file,不能是目录

具体举例如下:

[root@server ~]# [root@node ~]# ansible web -m fetch -a 'src=/test dest=fetch_test'
node3 | CHANGED => {
    "changed": true,
    "checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "dest": "/root/fetch_test/node3/test",
    "md5sum": "8ca7c11385856155af52e560f608891c",
    "remote_checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "remote_md5sum": null
}
node2 | CHANGED => {
    "changed": true,
    "checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "dest": "/root/fetch_test/node2/test",
    "md5sum": "8ca7c11385856155af52e560f608891c",
    "remote_checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "remote_md5sum": null
}
node1 | CHANGED => {
    "changed": true,
    "checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "dest": "/root/fetch_test/node1/test",
    "md5sum": "8ca7c11385856155af52e560f608891c",
    "remote_checksum": "064a68908ab9971ee85dbc08ea038387598e3778",
    "remote_md5sum": null
}

我们可以在本机上查看一下文件是否复制成功。要注意,文件保存的路径是我们设置的接收目录下的被管制主机ip目录下:

[root@node ~]# ls
anaconda-ks.cfg  fetch_test
[root@node ~]# ll fetch_test/
total 0
drwxr-xr-x 2 root root 18 Mar 31 23:50 node1
drwxr-xr-x 2 root root 18 Mar 31 23:50 node2
drwxr-xr-x 2 root root 18 Mar 31 23:50 node3

[root@node ~]# cd fetch_test/
[root@node fetch_test]# ls
node1  node2  node3
[root@node fetch_test]# cd node1
[root@node node1]# ls
test
[root@node node1]#

7)cron 模块
  该模块适用于管理cron计划任务的。
  其使用的语法跟我们的crontab文件中的语法一致,同时,可以指定以下选项:

day= #日应该运行的工作( 1-31, , /2, )
hour= # 小时 ( 0-23, , /2, )
minute= #分钟( 0-59, , /2, )
month= # 月( 1-12, *, /2, )
weekday= # 周 ( 0-6 for Sunday-Saturday, )
job= #指明运行的命令是什么
name= #定时任务描述
reboot # 任务在重启时运行,不建议使用,建议使用special_time
special_time #特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
state #指定状态,present表示添加定时任务,也是默认设置,absent表示删除定时任务
user # 以哪个用户的身份执行

举例如下:
① 添加计划任务

[root@node node1]# ansible web -m cron -a 'name="test" minute=*/5 job="/sbin/lsmod"'
node3 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": [
        "test"
    ]
}
node2 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": [
        "test"
    ]
}
node1 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": [
        "test"
    ]
}

我们可以去查看一下:

[root@node node1]# ansible web -m shell -a 'crontab -l'
node3 | CHANGED | rc=0 >>
#Ansible: test
*/5 * * * * /sbin/lsmod

node2 | CHANGED | rc=0 >>
#Ansible: test
*/5 * * * * /sbin/lsmod

node1 | CHANGED | rc=0 >>
#Ansible: test
*/5 * * * * /sbin/lsmod

可以看出,我们的计划任务已经设置成功了。
② 删除计划任务
  如果我们的计划任务添加错误,想要删除的话,则执行以下操作:
  首先我们查看一下现有的计划任务:

[root@node node1]# ansible web -m shell -a 'crontab -l'
node3 | CHANGED | rc=0 >>
#Ansible: test
*/5 * * * * /sbin/lsmod

node2 | CHANGED | rc=0 >>
#Ansible: test
*/5 * * * * /sbin/lsmod

node1 | CHANGED | rc=0 >>
#Ansible: test
*/5 * * * * /sbin/lsmod

然后执行删除操作:

[root@node node1]# ansible web -m cron -a 'name="test" state="absent"'
node2 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": []
}
node3 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": []
}
node1 | CHANGED => {
    "changed": true,
    "envs": [],
    "jobs": []
}

删除完成后,我们再查看一下现有的计划任务确认一下:

[root@node node1]# ansible web -m shell -a "crontab -l"
node1 | CHANGED | rc=0 >>


node3 | CHANGED | rc=0 >>


node2 | CHANGED | rc=0 >>

我们的删除操作已经成功。

8)yum 模块
  顾名思义,该模块主要用于软件的安装。
  其选项如下:

name= #所安装的包的名称
state= #present—>安装, latest—>安装最新的, absent—> 卸载软件。
update_cache #强制更新yum的缓存
conf_file #指定远程yum安装时所依赖的配置文件(安装本地已有的包)。
disable_pgp_check #是否禁止GPG checking,只用于presentor latest。
disablerepo #临时禁止使用yum库。 只用于安装或更新时。
enablerepo #临时使用的yum库。只用于安装或更新时。

下面我们就来安装一个包试试看:

[root@node node1]# ansible web -m yum -a 'name=wget state=present'
node2 | CHANGED => {
    "ansible_facts": {
        "pkg_mgr": "yum"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package wget.x86_64 0:1.14-15.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                   Repository    Size\n================================================================================\nInstalling:\n wget            x86_64            1.14-15.el7               c            547 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 547 k\nInstalled size: 2.0 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : wget-1.14-15.el7.x86_64                                      1/1 \n  Verifying  : wget-1.14-15.el7.x86_64                                      1/1 \n\nInstalled:\n  wget.x86_64 0:1.14-15.el7                                                     \n\nComplete!\n"
    ]
}
node3 | CHANGED => {
    "ansible_facts": {
        "pkg_mgr": "yum"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package wget.x86_64 0:1.14-15.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                   Repository    Size\n================================================================================\nInstalling:\n wget            x86_64            1.14-15.el7               c            547 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 547 k\nInstalled size: 2.0 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : wget-1.14-15.el7.x86_64                                      1/1 \n  Verifying  : wget-1.14-15.el7.x86_64                                      1/1 \n\nInstalled:\n  wget.x86_64 0:1.14-15.el7                                                     \n\nComplete!\n"
    ]
}
node1 | CHANGED => {
    "ansible_facts": {
        "pkg_mgr": "yum"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package wget.x86_64 0:1.14-15.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                   Repository    Size\n================================================================================\nInstalling:\n wget            x86_64            1.14-15.el7               c            547 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 547 k\nInstalled size: 2.0 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : wget-1.14-15.el7.x86_64                                      1/1 \n  Verifying  : wget-1.14-15.el7.x86_64                                      1/1 \n\nInstalled:\n  wget.x86_64 0:1.14-15.el7                                                     \n\nComplete!\n"
    ]
}

安装成功。

9)service 模块
  该模块用于服务程序的管理。
  其主要选项如下:

arguments #命令行提供额外的参数
enabled #设置开机启动。
name= #服务名称
runlevel #开机启动的级别,一般不用指定。
sleep #在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。(定义在剧本中。)
state #有四种状态,分别为:started—>启动服务, stopped—>停止服务, restarted—>重启服务, reloaded—>重载配置

下面是一些例子:
① 开启服务并设置自启动

[root@node node1]# ansible web -m service -a 'name=httpd state=started enabled=true'
node2 | CHANGED => {
    "changed": true,
    "enabled": true,
    "name": "httpd",
    "state": "started",
    "status": {
        "ActiveEnterTimestampMonotonic": "0",
        "ActiveExitTimestampMonotonic": "0",
        "ActiveState": "inactive",
        "After": "remote-fs.target -.mount tmp.mount nss-lookup.target network.target systemd-journald.socket basic.target system.slice",
        "AllowIsolate": "no",
        "AmbientCapabilities": "0",
        "AssertResult": "no",
        "AssertTimestampMonotonic": "0",
        "Before": "shutdown.target",
        "BlockIOAccounting": "no",
        "BlockIOWeight": "18446744073709551615",
        "CPUAccounting": "no",
        "CPUQuotaPerSecUSec": "infinity",
        "CPUSchedulingPolicy": "0",
        "CPUSchedulingPriority": "0",
        "CPUSchedulingResetOnFork": "no",
        "CPUShares": "18446744073709551615",
        "CanIsolate": "no",
        "CanReload": "yes",
        "CanStart": "yes",
        "CanStop": "yes",
        "CapabilityBoundingSet": "18446744073709551615",
        "ConditionResult": "no",
        "ConditionTimestampMonotonic": "0",
        "Conflicts": "shutdown.target",
        "ControlPID": "0",
        "DefaultDependencies": "yes",
        "Delegate": "no",
        "Description": "The Apache HTTP Server",
        "DevicePolicy": "auto",
        "Documentation": "man:httpd(8) man:apachectl(8)",
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)",
        "ExecMainCode": "0",
        "ExecMainExitTimestampMonotonic": "0",
        "ExecMainPID": "0",
        "ExecMainStartTimestampMonotonic": "0",
        "ExecMainStatus": "0",
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
        "FailureAction": "none",
        "FileDescriptorStoreMax": "0",
        "FragmentPath": "/usr/lib/systemd/system/httpd.service",
        "GuessMainPID": "yes",
        "IOScheduling": "0",
        "Id": "httpd.service",
        "IgnoreOnIsolate": "no",
        "IgnoreOnSnapshot": "no",
        "IgnoreSIGPIPE": "yes",
        "InactiveEnterTimestampMonotonic": "0",
        "InactiveExitTimestampMonotonic": "0",
        "JobTimeoutAction": "none",
        "JobTimeoutUSec": "0",
        "KillMode": "control-group",
        "KillSignal": "18",
        "LimitAS": "18446744073709551615",
        "LimitCORE": "18446744073709551615",
        "LimitCPU": "18446744073709551615",
        "LimitDATA": "18446744073709551615",
        "LimitFSIZE": "18446744073709551615",
        "LimitLOCKS": "18446744073709551615",
        "LimitMEMLOCK": "65536",
        "LimitMSGQUEUE": "819200",
        "LimitNICE": "0",
        "LimitNOFILE": "4096",
        "LimitNPROC": "3828",
        "LimitRSS": "18446744073709551615",
        "LimitRTPRIO": "0",
        "LimitRTTIME": "18446744073709551615",
        "LimitSIGPENDING": "3828",
        "LimitSTACK": "18446744073709551615",
        "LoadState": "loaded",
        "MainPID": "0",
        "MemoryAccounting": "no",
        "MemoryCurrent": "18446744073709551615",
        "MemoryLimit": "18446744073709551615",
        "MountFlags": "0",
        "Names": "httpd.service",
        "NeedDaemonReload": "no",
        "Nice": "0",
        "NoNewPrivileges": "no",
        "NonBlocking": "no",
        "NotifyAccess": "main",
        "OOMScoreAdjust": "0",
        "OnFailureJobMode": "replace",
        "PermissionsStartOnly": "no",
        "PrivateDevices": "no",
        "PrivateNetwork": "no",
        "PrivateTmp": "yes",
        "ProtectHome": "no",
        "ProtectSystem": "no",
        "RefuseManualStart": "no",
        "RefuseManualStop": "no",
        "RemainAfterExit": "no",
        "Requires": "basic.target -.mount",
        "RequiresMountsFor": "/var/tmp",
        "Restart": "no",
        "RestartUSec": "100ms",
        "Result": "success",
        "RootDirectoryStartOnly": "no",
        "RuntimeDirectoryMode": "0755",
        "SameProcessGroup": "no",
        "SecureBits": "0",
        "SendSIGHUP": "no",
        "SendSIGKILL": "yes",
        "Slice": "system.slice",
        "StandardError": "inherit",
        "StandardInput": "null",
        "StandardOutput": "journal",
        "StartLimitAction": "none",
        "StartLimitBurst": "5",
        "StartLimitInterval": "10000000",
        "StartupBlockIOWeight": "18446744073709551615",
        "StartupCPUShares": "18446744073709551615",
        "StatusErrno": "0",
        "StopWhenUnneeded": "no",
        "SubState": "dead",
        "SyslogLevelPrefix": "yes",
        "SyslogPriority": "30",
        "SystemCallErrorNumber": "0",
        "TTYReset": "no",
        "TTYVHangup": "no",
        "TTYVTDisallocate": "no",
        "TasksAccounting": "no",
        "TasksCurrent": "18446744073709551615",
        "TasksMax": "18446744073709551615",
        "TimeoutStartUSec": "1min 30s",
        "TimeoutStopUSec": "1min 30s",
        "TimerSlackNSec": "50000",
        "Transient": "no",
        "Type": "notify",
        "UMask": "0022",
        "UnitFilePreset": "disabled",
        "UnitFileState": "disabled",
        "Wants": "system.slice",
        "WatchdogTimestampMonotonic": "0",
        "WatchdogUSec": "0"
    }
}

我们可以去查看一下端口是否打开:

[root@node node1]# ansible web -m shell -a 'ss -ntl'
node3 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128         :::80                      :::*
LISTEN     0      128         :::22                      :::*
LISTEN     0      100        ::1:25                      :::*

node2 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128         :::80                      :::*
LISTEN     0      128         :::22                      :::*
LISTEN     0      100        ::1:25                      :::*

node1 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128         :::80                      :::*
LISTEN     0      128         :::22                      :::*
LISTEN     0      100        ::1:25                   

可以看出我们的80端口已经打开。
② 关闭服务
  我们也可以通过该模块来关闭我们的服务:

[root@node node1]# ansible web -m service -a 'name=httpd state=stopped'
node2 | CHANGED => {
    "changed": true,
    "name": "httpd",
    "state": "stopped",
    "status": {
        "ActiveEnterTimestamp": "Mon 2019-04-01 00:10:41 EDT",
        "ActiveEnterTimestampMonotonic": "27349639976",
        "ActiveExitTimestampMonotonic": "0",
        "ActiveState": "active",
        "After": "basic.target tmp.mount systemd-journald.socket system.slice network.target remote-fs.target nss-lookup.target -.mount",
        "AllowIsolate": "no",
        "AmbientCapabilities": "0",
        "AssertResult": "yes",

一样的,我们来查看一下端口:

[root@node node1]# ansible web -m shell -a 'ss -ntl'
node2 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128         :::22                      :::*
LISTEN     0      100        ::1:25                      :::*

node1 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128         :::22                      :::*
LISTEN     0      100        ::1:25                      :::*

node3 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port
LISTEN     0      128          *:22                       *:*
LISTEN     0      100    127.0.0.1:25                       *:*
LISTEN     0      128         :::22                      :::*
LISTEN     0      100        ::1:25                      :::*

可以看出,我们已经没有80端口了,说明我们的httpd服务已经关闭了。

10)user 模块

该模块主要是用来管理用户账号。
  其主要选项如下:

comment # 用户的描述信息
createhome # 是否创建家目录
force # 在使用state=absent时, 行为与userdel –force一致.
group # 指定基本组
groups # 指定附加组,如果指定为(groups=)表示删除所有组
home # 指定用户家目录
move_home # 如果设置为home=时, 试图将用户主目录移动到指定的目录
name # 指定用户名
non_unique # 该选项允许改变非唯一的用户ID值
password # 指定用户密码
remove # 在使用state=absent时, 行为是与userdel –remove一致
shell # 指定默认shell
state # 设置帐号状态,不指定为创建,指定值为absent表示删除
system # 当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户
uid # 指定用户的uid

举例如下:
① 添加一个用户并指定其 uid

[root@node node1]# ansible web -m user -a 'name=cwf uid=11111'
node2 | CHANGED => {
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 11111,
    "home": "/home/cwf",
    "name": "cwf",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 11111
}
node3 | CHANGED => {
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 11111,
    "home": "/home/cwf",
    "name": "cwf",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 11111
}
node1 | CHANGED => {
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 11111,
    "home": "/home/cwf",
    "name": "cwf",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 11111
}

添加完成,我们可以去查看一下:

[root@node node1]# ansible web -m shell -a 'cat /etc/passwd |grep cwf'
node3 | CHANGED | rc=0 >>
cwf:x:11111:11111::/home/cwf:/bin/bash

node2 | CHANGED | rc=0 >>
cwf:x:11111:11111::/home/cwf:/bin/bash

node1 | CHANGED | rc=0 >>
cwf:x:11111:11111::/home/cwf:/bin/bash

② 删除用户

[root@node node1]# ansible web -m user -a 'name=cwf state=absent'
node1 | CHANGED => {
    "changed": true,
    "force": false,
    "name": "cwf",
    "remove": false,
    "state": "absent"
}
node2 | CHANGED => {
    "changed": true,
    "force": false,
    "name": "cwf",
    "remove": false,
    "state": "absent"
}
node3 | CHANGED => {
    "changed": true,
    "force": false,
    "name": "cwf",
    "remove": false,
    "state": "absent"
}

11)group 模块
  该模块主要用于添加或删除组。
  常用的选项如下:

gid= #设置组的GID号
name= #指定组的名称
state= #指定组的状态,默认为创建,设置值为absent为删除
system= #设置值为yes,表示创建为系统组

举例如下:
① 创建组

[root@node node1]# ansible web -m group -a 'name=test gid=12222'
node1 | CHANGED => {
    "changed": true,
    "gid": 12222,
    "name": "test",
    "state": "present",
    "system": false
}
node3 | CHANGED => {
    "changed": true,
    "gid": 12222,
    "name": "test",
    "state": "present",
    "system": false
}
node2 | CHANGED => {
    "changed": true,
    "gid": 12222,
    "name": "test",
    "state": "present",
    "system": false
}

创建过后,我们来查看一下:

[root@node node1]# ansible web -m shell -a 'cat /etc/group | grep 12222'
node2 | CHANGED | rc=0 >>
test:x:12222:

node3 | CHANGED | rc=0 >>
test:x:12222:

node1 | CHANGED | rc=0 >>
test:x:12222:

可以看出,我们的组已经创建成功了。
② 删除组

[root@node node1]# ansible web -m group -a 'name=test state=absent'
node2 | CHANGED => {
    "changed": true,
    "name": "test",
    "state": "absent"
}
node1 | CHANGED => {
    "changed": true,
    "name": "test",
    "state": "absent"
}
node3 | CHANGED => {
    "changed": true,
    "name": "test",
    "state": "absent"
}

照例查看一下:

[root@node node1]# ansible web -m shell -a 'cat /etc/group | grep 12222'
node2 | FAILED | rc=1 >>
non-zero return code

node3 | FAILED | rc=1 >>
non-zero return code

node1 | FAILED | rc=1 >>
non-zero return code

已经没有这个组的相关信息了。

12)script 模块
  该模块用于将本机的脚本在被管理端的机器上运行。
  该模块直接指定脚本的路径即可,我们通过例子来看一看到底如何使用的:
  首先,我们写一个脚本,并给其加上执行权限:

[root@node /]# vi test.sh
[root@node /]# chmod +x test.sh
[root@node /]# cat test.sh
#!/bin/bash
date >> /tmp/disk_total.log
df -lh >> /tmp/disk_total.log



[root@node /]# ansible web -m script -a '/test.sh'
node1 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to node1 closed.\r\n",
    "stderr_lines": [
        "Shared connection to node1 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}
node2 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to node2 closed.\r\n",
    "stderr_lines": [
        "Shared connection to node2 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}
node3 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to node3 closed.\r\n",
    "stderr_lines": [
        "Shared connection to node3 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}

照例查看一下文件内容:

[root@node /]#  ansible web -m shell -a 'cat /tmp/disk_total.log'
node1 | CHANGED | rc=0 >>
Mon Apr  1 00:29:27 EDT 2019
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        18G  959M   17G   6% /
devtmpfs        479M     0  479M   0% /dev
tmpfs           489M     0  489M   0% /dev/shm
tmpfs           489M  6.9M  482M   2% /run
tmpfs           489M     0  489M   0% /sys/fs/cgroup
/dev/sr0        4.3G  4.3G     0 100% /mnt
/dev/sda1       197M   97M  100M  50% /boot
tmpfs            98M     0   98M   0% /run/user/0

node2 | CHANGED | rc=0 >>
Mon Apr  1 00:29:28 EDT 2019
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        18G  959M   17G   6% /
devtmpfs        479M     0  479M   0% /dev
tmpfs           489M     0  489M   0% /dev/shm
tmpfs           489M  6.8M  482M   2% /run
tmpfs           489M     0  489M   0% /sys/fs/cgroup
/dev/sr0        4.3G  4.3G     0 100% /mnt
/dev/sda1       197M   97M  100M  50% /boot
tmpfs            98M     0   98M   0% /run/user/0

node3 | CHANGED | rc=0 >>
Mon Apr  1 00:29:28 EDT 2019
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        18G  959M   17G   6% /
devtmpfs        479M     0  479M   0% /dev
tmpfs           489M     0  489M   0% /dev/shm
tmpfs           489M  6.8M  482M   2% /run
tmpfs           489M     0  489M   0% /sys/fs/cgroup
/dev/sr0        4.3G  4.3G     0 100% /mnt
/dev/sda1       197M   97M  100M  50% /boot
tmpfs            98M     0   98M   0% /run/user/0

可以看出已经执行成功了。

13)setup 模块
  该模块主要用于收集信息,是通过调用facts组件来实现的。
  facts组件是Ansible用于采集被管机器设备信息的一个功能,我们可以使用setup模块查机器的所有facts信息,可以使用filter来查看指定信息。整个facts信息被包装在一个JSON格式的数据结构中,ansible_facts是最上层的值。
  facts就是变量,内建变量 。每个主机的各种信息,cpu颗数、内存大小等。会存在facts中的某个变量中。调用后返回很多对应主机的信息,在后面的操作中可以根据不同的信息来做不同的操作。如redhat系列用yum安装,而debian系列用apt来安装软件。
① 查看信息
  我们可以直接用命令获取到变量的值,具体我们来看看例子:

[root@node /]#  ansible web -m setup -a 'filter="*mem*"'
node3 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 647,
        "ansible_memory_mb": {
            "nocache": {
                "free": 825,
                "used": 151
            },
            "real": {
                "free": 647,
                "total": 976,
                "used": 329
            },
            "swap": {
                "cached": 0,
                "free": 2047,
                "total": 2047,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 976
    },
    "changed": false
}
node1 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 647,
        "ansible_memory_mb": {
            "nocache": {
                "free": 825,
                "used": 151
            },
            "real": {
                "free": 647,
                "total": 976,
                "used": 329
            },
            "swap": {
                "cached": 0,
                "free": 2047,
                "total": 2047,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 976
    },
    "changed": false
}
node2 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 646,
        "ansible_memory_mb": {
            "nocache": {
                "free": 824,
                "used": 152
            },
            "real": {
                "free": 646,
                "total": 976,
                "used": 330
            },
            "swap": {
                "cached": 0,
                "free": 2047,
                "total": 2047,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 976
    },
    "changed": false
}

② 保存信息
  我们的setup模块还有一个很好用的功能就是可以保存我们所筛选的信息至我们的主机上,同时,文件名为我们被管制的主机的IP,这样方便我们知道是哪台机器出的问题。
  我们可以看一看例子:

[root@node /]# ansible web -m setup -a 'filter="*mem*"' --tree /tmp/facts
node3 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 645,
        "ansible_memory_mb": {
            "nocache": {
                "free": 824,
                "used": 152
            },
            "real": {
                "free": 645,
                "total": 976,
                "used": 331
            },
            "swap": {
                "cached": 0,
                "free": 2047,
                "total": 2047,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 976
    },
    "changed": false
}
node2 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 645,
        "ansible_memory_mb": {
            "nocache": {
                "free": 824,
                "used": 152
            },
            "real": {
                "free": 645,
                "total": 976,
                "used": 331
            },
            "swap": {
                "cached": 0,
                "free": 2047,
                "total": 2047,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 976
    },
    "changed": false
}
node1 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 646,
        "ansible_memory_mb": {
            "nocache": {
                "free": 825,
                "used": 151
            },
            "real": {
                "free": 646,
                "total": 976,
                "used": 330
            },
            "swap": {
                "cached": 0,
                "free": 2047,
                "total": 2047,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 976
    },
    "changed": false
}

然后我们可以去查看一下:

[root@node /]# cd /tmp/facts/
[root@node facts]# ls
node1  node2  node3
[root@node facts]# cat node1
{"ansible_facts": {"ansible_memfree_mb": 646, "ansible_memory_mb": {"nocache": {"free": 825, "used": 151}, "real": {"free": 646, "total":  976, "used": 330}, "swap": {"cached": 0, "free": 2047, "total": 2047, "used": 0}}, "ansible_memtotal_mb": 976},

你可能感兴趣的:(ansible从入门到实践(一))