一、简介:
1、什么是Ansible
Ansible 是一个简单,强大且无代理的自动化语言。
Ansible 的好处:
简单易读:基于 YAML 文本编写,易于阅读,非专业的开发人员也可以编写。
功能强大:它可以同于管理配置,软件安装,流程自动化
无代理:不需要在客户端安装额外的agent
跨平台支持:支持 linux,Windows,Unix 和网络设备
2、Ansible 是如何工作的
Ansible 典型的工作方式是通过一个脚本文件(基于 YAML 格式构建的)去控制远端操作系统按照特定的顺序执行相关任务,我们称这个文件为 playbook;
3、Ansible架构
Ansible 架构中拥有两种计算机类型,即控制节点和受控节点。Ansible 运行在控制节点上,并且只能运行在 linux 操作系统上,对于被控节点,可以是主机设备,也可以是网络设备,主机设备的操作系统,可以是 Windows,也可以是 linux。
清单(inventory): 受控节点设备的列表。在这个列表中,你可以根据某些标准(如,作用,服务等)将拥有相同属性的计算机组织到一个组中。Ansible 清单,支持静态清单(一旦定义好,除非你修改配置文件,不然不会发生改变。),也支持动态清单(通过脚本从外部源获取清单,该清单可以随着环境的改变而改变)
Playbook: 需要在被控节点主机上运行的任务列表,从而让他们达到我们预期的状态。Playbook 中包含一个或多个 play,每个 play 会在一组或多组计算机上按顺序执行已经定义好的一系列 task,每个 task 都是一个执行模块。
模块(Module): 用于确保主机处于某一个特定的状态,例如可以使用yum(对于不同发行版本的 Linux,模块名可能有所不同个,如,在 Ubuntu 中与之对应的是 apt 模块。) 模块确保主机已经安装了某个软件,如果主机状态已经是预期的了(已经安装了该软件),那么就不会执行任何操作,执行下一个模块(task)
Plugin: 添加到 Ansible 中的代码段,用于扩展 Ansible 平台
二、安装(本文只限本地安装)
1、配置本地yum源
2、安装python(此处为了方便直接全部安装,省的后面缺失很多依赖包)
yum install -y python*
3、下载安装相关依赖包,并安装ansible
--------相关依赖包如下,直接到https://centos.pkgs.org/ 查找下载即可--------
[root@linux1 ansible]# ll
total 19472
-rw-r--r--. 1 root root 17832207 Nov 30 02:40 ansible-2.9.27-1.el7.noarch.rpm
-rw-r--r--. 1 root root 56068 Nov 30 02:40 libyaml-0.1.4-11.el7_0.x86_64.rpm
-rw-r--r--. 1 root root 514504 Nov 30 02:40 python2-cryptography-1.7.2-2.el7.x86_64.rpm
-rw-r--r--. 1 root root 117968 Nov 30 02:40 python-httplib2-0.9.2-1.el7.noarch.rpm
-rw-r--r--. 1 root root 531040 Nov 30 02:40 python-jinja2-2.7.2-4.el7.noarch.rpm
-rw-r--r--. 1 root root 275112 Nov 30 02:40 python-paramiko-2.1.1-9.el7.noarch.rpm
-rw-r--r--. 1 root root 406404 Nov 30 02:40 python-setuptools-0.9.8-7.el7.noarch.rpm
-rw-r--r--. 1 root root 29404 Nov 30 02:40 python-six-1.9.0-2.el7.noarch.rpm
-rw-r--r--. 1 root root 156952 Nov 30 02:40 PyYAML-3.10-11.el7.x86_64.rpm
-rw-r--r--. 1 root root 21896 Nov 30 02:40 sshpass-1.06-2.el7.x86_64.rpm
-rw-r--r--. 1 root root 39576 Nov 30 02:40 python2-jmespath-0.9.0-3.el7.noarch.rpm
--------安装依赖包,其中有部分包在前面第一步安装python时已经安装过,忽略即可------
[root@linux1 ansible]#
[root@linux1 ansible]# rpm -ivh libyaml-0.1.4-11.el7_0.x86_64.rpm
warning: libyaml-0.1.4-11.el7_0.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
Updating / installing...
1:libyaml-0.1.4-11.el7_0 ################################# [100%]
[root@linux1 ansible]# rpm -ivh python2-cryptography-1.7.2-2.el7.x86_64.rpm
warning: python2-cryptography-1.7.2-2.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
package python2-cryptography-1.7.2-2.el7.x86_64 is already installed
[root@linux1 ansible]# rpm -ivh python-httplib2-0.9.2-1.el7.noarch.rpm
warning: python-httplib2-0.9.2-1.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
Updating / installing...
1:python-httplib2-0.9.2-1.el7 ################################# [100%]
[root@linux1 ansible]# rpm -ivh python-jinja2-2.7.2-4.el7.noarch.rpm
warning: python-jinja2-2.7.2-4.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
package python-jinja2-2.7.2-4.el7.noarch is already installed
[root@linux1 ansible]# rpm -ivh python-paramiko-2.1.1-9.el7.noarch.rpm
warning: python-paramiko-2.1.1-9.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
package python-paramiko-2.1.1-9.el7.noarch is already installed
[root@linux1 ansible]# rpm -ivh python-setuptools-0.9.8-7.el7.noarch.rpm
warning: python-setuptools-0.9.8-7.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
package python-setuptools-0.9.8-7.el7.noarch is already installed
[root@linux1 ansible]# rpm -ivh python-setuptools-0.9.8-7.el7.noarch.rpm
warning: python-setuptools-0.9.8-7.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
package python-setuptools-0.9.8-7.el7.noarch is already installed
[root@linux1 ansible]# rpm -ivh PyYAML-3.10-11.el7.x86_64.rpm
warning: PyYAML-3.10-11.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
Updating / installing...
1:PyYAML-3.10-11.el7 ################################# [100%]
[root@linux1 ansible]# rpm -ivh sshpass-1.06-2.el7.x86_64.rpm
warning: sshpass-1.06-2.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
Updating / installing...
1:sshpass-1.06-2.el7 ################################# [100%]
[root@linux1 ansible]# rpm -ivh python2-jmespath-0.9.0-3.el7.noarch.rpm
warning: python2-jmespath-0.9.0-3.el7.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Preparing... ################################# [100%]
Updating / installing...
1:python2-jmespath-0.9.0-3.el7 ################################# [100%]
---------安装ansible包----------
[root@linux1 ansible]# rpm -ivh ansible-2.9.27-1.el7.noarch.rpm
warning: ansible-2.9.27-1.el7.noarch.rpm: Header V4 RSA/SHA256 Signature, key ID 352c64e5: NOKEY
Preparing... ################################# [100%]
Updating / installing...
1:ansible-2.9.27-1.el7 ################################# [100%]
[root@linux1 ansible]#
[root@linux1 ansible]#
--------安装完成,检验是否安装成功--------
[root@linux1 ansible]# ansible
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
[--become-user BECOME_USER] [-K] [-i INVENTORY] [--list-hosts]
[-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [-k]
[--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER]
[-c CONNECTION] [-T TIMEOUT]
[--ssh-common-args SSH_COMMON_ARGS]
[--sftp-extra-args SFTP_EXTRA_ARGS]
[--scp-extra-args SCP_EXTRA_ARGS]
[--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
[-e EXTRA_VARS] [--vault-id VAULT_IDS]
[--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
[-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR]
[-a MODULE_ARGS] [-m MODULE_NAME]
pattern
ansible: error: too few arguments
[root@linux1 ansible]#
[root@linux1 ansible]# ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Oct 14 2020, 14:45:30) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
三、结构与配置
1、安装目录
配置文件目录:/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/
2、Ansible配置文件查找顺序
检查环境变量ANSIBLE_CONFIG指向的路径文件(export ANSIBLE_CONFIG=/etc/ansible.cfg);
~/.ansible.cfg,检查当前目录下的ansible.cfg配置文件;
/etc/ansible/ansible.cfg 检查etc目录的配置文件。
3、Ansible配置文件
默认配置文件为/etc/ansible/ansible.cfg,常用的配置选项如下:
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日志的文件(默认不记录日志)
4、Ansible主机清单
主机清单即/etc/ansible/hosts文件,里面保留了ansible需要管理的主机列表,定义方式如下:
----------第一种方式,加标签,方便分组管理-----------
[mysql]
192.168.10.12
192.168.10.13
[oracle]
192.168.10.14
192.168.10.13
[php]
192.168.10.[11:14] #此写法表示11到14,也就是11,12,13,14
----------第二种方式,直接写全部ip-----------
192.168.10.11
192.168.10.12
192.168.10.13
192.168.10.14
192.168.10.2[1:9] #此写法表示模糊匹配,21到29
5、Ansible公钥配置
由于ansible 是基于 ssh 协议实现的,所以需要配置公钥到被管理节点,以实现ssh登录。通过创建并执行以下脚本,即可完成主机公钥配置
vi ssh_pass.sh #将下面内容粘贴到ssh_pass.sh脚本中,其中IPLIST是你的主机列表,SSHPASS是主机的root密码
#!/bin/bash
IPLIST="
192.168.10.12
192.168.10.13
192.168.10.14"
rpm -q sshpass &> /dev/null || yum install -y sshpass
[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa -P ''
export SSHPASS=123456
for IP in $IPLIST;do
sshpass -e ssh-copy-id -o StrictHostKeyChecking=no $IP
done
--------为脚本增加执行权限,并执行,执行成功后即可验证-----------
[root@linux1 ~]# chmod +x ssh_passh.sh
[root@linux1 ~]# ./ssh_passh.sh
--------验证公钥是否配置成功-----------
[root@linux1 ansible]# ansible all -m ping
192.168.10.13 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.10.14 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.10.12 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
四、常用命令
1、命令格式
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 #查看详细信息,同时支持-vv,-vvv可查看更详细信息
2、常用模块示例
1) 主机连通性测试
使用命令: ansible mysql -m ping 命令来测试主机联通性,mysql是hosts文件中的一个标签
[root@linux1 ansible]# ansible mysql -m ping
192.168.10.12 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.10.13 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
2) command 模块
这个模块可以直接在远程主机上执行命令,并将结果返回本主机。
示例如下:
[root@linux1 ansible]# ansible oracle -m command -a 'free -m'
192.168.10.13 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 972 313 74 7 584 471
Swap: 2047 0 2047
192.168.10.14 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 972 184 642 7 145 641
Swap: 3999 0 3999
命令模块接受命令名称,后面是空格分隔的列表参数。给定的命令将在所有选定的节点上执行。它不会通过shell进行处理,比如$HOME和操作如"<“,”>“,”|“,”;“,”&" 的工作(需要使用(shell)模块实现这些功能)。注意,该命令不支持| 管道命令。
该模块常用的有下面几个命令:
chdir # 在执行命令之前,先切换到该目录
executable # 切换shell来执行命令,需要使用命令的绝对路径
free_form # 要执行的Linux指令,一般使用Ansible的-a参数代替。
creates # 一个文件名,当这个文件存在,则该命令不执行,可以用来做判断
removes # 一个文件名,这个文件不存在,则该命令不执行
[root@linux1 ansible]# ansible mysql -m command -a 'chdir=/data ls' #chdir,切换到/data目录下执行ls
192.168.10.12 | CHANGED | rc=0 >>
app
mysql57
192.168.10.13 | CHANGED | rc=0 >>
app
mysql57
[root@linux1 ansible]# ansible mysql -m command -a 'creates=/data/1.txt ls /data' #creates,文件存在则命令不执行,因为1.txt不存,所以执行了 ls /data
192.168.10.12 | CHANGED | rc=0 >>
app
mysql57
192.168.10.13 | CHANGED | rc=0 >>
app
mysql57
-----分别在mysql的两台主机下的/data目录下touch文件a后再次测试-----
[root@linux1 ansible]# ansible mysql -m command -a 'creates=/data/a ls /data' #文件存在则不执行,由于/data/a存在,所以不执行
192.168.10.12 | SUCCESS | rc=0 >>
skipped, since /data/a exists
192.168.10.13 | SUCCESS | rc=0 >>
skipped, since /data/a exists
[root@linux1 ansible]# ansible mysql -m command -a 'removes=/data/a ls /data' # removes,文件不存在则命令不执行,由于a文件存在,所以要执行ls /data
192.168.10.12 | CHANGED | rc=0 >>
a
app
mysql57
192.168.10.13 | CHANGED | rc=0 >>
a
app
mysql57
3) shell 模块
shell模块可以在远程主机上调用shell解释器运行命令,支持shell的各种功能,例如管道等
[root@linux1 ansible]# ansible mysql -m shell -a 'ps -ef |grep mysql'
192.168.10.12 | CHANGED | rc=0 >>
root 31006 31005 0 23:20 pts/1 00:00:00 /bin/sh -c ps -ef |grep mysql
root 31008 31006 0 23:20 pts/1 00:00:00 grep mysql
192.168.10.13 | CHANGED | rc=0 >>
root 37819 37814 0 04:59 pts/2 00:00:00 /bin/sh -c ps -ef |grep mysql
root 37821 37819 0 04:59 pts/2 00:00:00 grep mysql
4) copy 模块
这个模块用于将文件复制到远程主机,同时支持给定内容生成文件和修改权限等,其相关选项如下:
src #被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"
content #用于替换"src",可以直接指定文件的值
dest #必选项,将源文件复制到的远程主机的绝对路径
backup #当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息
directory_mode #递归设定目录的权限,默认为系统默认权限
force #当目标主机包含该文件,但内容不同时,设为"yes",表示强制覆盖;设为"no",表示目标主机的目标位置不存在该文件才复制。默认为"yes"
others #所有的 file 模块中的选项可以在这里使用
-----------拷贝本地文件到远程主机-------
[root@linux1 ansible]# ansible mysql -m copy -a 'src=./hello dest=/data/hello'
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "633dd839e18ee0526aa1ade583609f96f96c5d75",
"dest": "/data/hello",
"gid": 0,
"group": "root",
"md5sum": "6712d37aa87793567d3649f1f2c791ca",
"mode": "0644",
"owner": "root",
"size": 10,
"src": "/root/.ansible/tmp/ansible-tmp-1669735541.59-38875-216260739708380/source",
"state": "file",
"uid": 0
}
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "633dd839e18ee0526aa1ade583609f96f96c5d75",
"dest": "/data/hello",
"gid": 0,
"group": "root",
"md5sum": "6712d37aa87793567d3649f1f2c791ca",
"mode": "0644",
"owner": "root",
"secontext": "system_u:object_r:default_t:s0",
"size": 10,
"src": "/root/.ansible/tmp/ansible-tmp-1669735542.0-38876-200379872067597/source",
"state": "file",
"uid": 0
}
-----------给定内容生成文件,并指定权限-------
[root@linux1 ansible]# ansible mysql -m copy -a 'content="A B C\n" dest=/data/abc mode=755'
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "210aac1c70d730fefd94048e4020725054fb4e10",
"dest": "/data/abc",
"gid": 0,
"group": "root",
"md5sum": "e2c09866c720d8c96020d9074c9edd85",
"mode": "0755",
"owner": "root",
"secontext": "system_u:object_r:default_t:s0",
"size": 6,
"src": "/root/.ansible/tmp/ansible-tmp-1669735657.86-39041-169973779825842/source",
"state": "file",
"uid": 0
}
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "210aac1c70d730fefd94048e4020725054fb4e10",
"dest": "/data/abc",
"gid": 0,
"group": "root",
"md5sum": "e2c09866c720d8c96020d9074c9edd85",
"mode": "0755",
"owner": "root",
"size": 6,
"src": "/root/.ansible/tmp/ansible-tmp-1669735657.54-39039-180273510264764/source",
"state": "file",
"uid": 0
}
-------------查看上面生成的文件及其权限----------
[root@linux1 ansible]# ansible mysql -m shell -a 'ls -l /data/abc'
192.168.10.13 | CHANGED | rc=0 >>
-rwxr-xr-x. 1 root root 6 Nov 30 05:06 /data/abc
192.168.10.12 | CHANGED | rc=0 >>
-rwxr-xr-x 1 root root 6 Nov 29 23:27 /data/abc
[root@linux1 ansible]#
-------------修改内容,备份后替换----------
[root@linux1 ansible]# ansible mysql -m copy -a 'content="A B C D\n" backup=yes dest=/data/abc mode=666'
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"backup_file": "/data/abc.38593.2022-11-30@05:11:27~",
"changed": true,
"checksum": "5d96d9ca1157ab35684544ebccb92587c735a7bf",
"dest": "/data/abc",
"gid": 0,
"group": "root",
"md5sum": "3c96e5169486f07524a2e2fde1b74002",
"mode": "0666",
"owner": "root",
"secontext": "system_u:object_r:default_t:s0",
"size": 8,
"src": "/root/.ansible/tmp/ansible-tmp-1669735940.74-39443-245102005460999/source",
"state": "file",
"uid": 0
}
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"backup_file": "/data/abc.32772.2022-11-29@23:32:22~",
"changed": true,
"checksum": "5d96d9ca1157ab35684544ebccb92587c735a7bf",
"dest": "/data/abc",
"gid": 0,
"group": "root",
"md5sum": "3c96e5169486f07524a2e2fde1b74002",
"mode": "0666",
"owner": "root",
"size": 8,
"src": "/root/.ansible/tmp/ansible-tmp-1669735940.39-39442-238016667304130/source",
"state": "file",
"uid": 0
}
-------------查看新文件及原文件备份----------
[root@linux1 ansible]# ansible mysql -m shell -a 'ls -l /data' #可以看到abc文件有个备份
192.168.10.12 | CHANGED | rc=0 >>
total 16
-rw-r--r-- 1 root root 0 Nov 29 23:13 a
-rw-rw-rw- 1 root root 8 Nov 29 23:32 abc
-rwxr-xr-x 1 root root 6 Nov 29 23:27 abc.32772.2022-11-29@23:32:22~
-rw-r--r-- 1 root root 10 Nov 29 23:25 hello
drwxr-xr-x. 6 mysql mysql 4096 Nov 29 17:59 mysql57
192.168.10.13 | CHANGED | rc=0 >>
total 16
-rw-r--r--. 1 root root 0 Nov 30 04:52 a
-rw-rw-rw-. 1 root root 8 Nov 30 05:11 abc
-rwxr-xr-x. 1 root root 6 Nov 30 05:06 abc.38593.2022-11-30@05:11:27~
-rw-r--r--. 1 root root 10 Nov 30 05:04 hello
drwxr-xr-x. 5 mysql mysql 4096 Nov 30 01:59 mysql57
5) file 模块
该模块主要用于设置文件的属性,比如创建文件、创建链接文件、删除文件等,常见命令如下:
force #需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group #定义文件/目录的属组。后面可以加上mode:定义文件/目录的权限
owner #定义文件/目录的属主。后面必须跟上path:定义文件/目录的路径
recurse #递归设置文件的属性,只对目录有效,后面跟上src:被链接的源文件路径,只应用于state=link的情况
dest #被链接到的路径,只应用于state=link的情况
state #状态,有以下选项:
directory:如果目录不存在,就创建目录
file:即使文件不存在,也不会被创建
link:创建软链接
hard:创建硬链接
touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
absent:删除目录、文件或者取消链接文件
-----------创建目录---------
[root@linux1 ansible]# ansible mysql -m file -a 'path=/data/app1 state=directory'
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/data/app1",
"secontext": "unconfined_u:object_r:default_t:s0",
"size": 6,
"state": "directory",
"uid": 0
}
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/data/app1",
"size": 6,
"state": "directory",
"uid": 0
}
--------------创建软连接文件---------
[root@linux1 ansible]# ansible mysql -m file -a 'path=/data/abc.link src=abc state=link'
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/data/abc.link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"secontext": "unconfined_u:object_r:default_t:s0",
"size": 3,
"src": "abc",
"state": "link",
"uid": 0
}
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/data/abc.link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 3,
"src": "abc",
"state": "link",
"uid": 0
}
--------------查看刚才创建的文件及目录-------
[root@linux1 ansible]# ansible mysql -m shell -a 'ls -l /data'
192.168.10.13 | CHANGED | rc=0 >>
total 16
-rw-r--r--. 1 root root 0 Nov 30 04:52 a
-rw-rw-rw-. 1 root root 8 Nov 30 05:11 abc
-rwxr-xr-x. 1 root root 6 Nov 30 05:06 abc.38593.2022-11-30@05:11:27~
lrwxrwxrwx. 1 root root 3 Nov 30 05:24 abc.link -> abc
drwxr-xr-x. 2 root root 6 Nov 30 05:22 app1
-rw-r--r--. 1 root root 10 Nov 30 05:04 hello
drwxr-xr-x. 5 mysql mysql 4096 Nov 30 01:59 mysql57
192.168.10.12 | CHANGED | rc=0 >>
total 16
-rw-r--r-- 1 root root 0 Nov 29 23:13 a
-rw-rw-rw- 1 root root 8 Nov 29 23:32 abc
-rwxr-xr-x 1 root root 6 Nov 29 23:27 abc.32772.2022-11-29@23:32:22~
lrwxrwxrwx 1 root root 3 Nov 29 23:45 abc.link -> abc
drwxr-xr-x 2 root root 6 Nov 29 23:43 app1
-rw-r--r-- 1 root root 10 Nov 29 23:25 hello
drwxr-xr-x. 6 mysql mysql 4096 Nov 29 17:59 mysql57
--------------删除文件-------
[root@linux1 ansible]# ansible mysql -m file -a 'path=/data/app1 state=absent'
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/data/app1",
"state": "absent"
}
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/data/app1",
"state": "absent"
}
6) fetch 模块
该模块用于从远程某主机获取(复制)文件到本地,有两个选项
dest:用来存放文件的目录
src:在远程拉取的文件,并且必须是一个file,不能是目录
----------从远程拉取文件--------
[root@linux1 data]# ansible mysql -m fetch -a 'src=/data/abc dest=/data'
192.168.10.12 | CHANGED => {
"changed": true,
"checksum": "5d96d9ca1157ab35684544ebccb92587c735a7bf",
"dest": "/data/192.168.10.12/data/abc",
"md5sum": "3c96e5169486f07524a2e2fde1b74002",
"remote_checksum": "5d96d9ca1157ab35684544ebccb92587c735a7bf",
"remote_md5sum": null
}
192.168.10.13 | CHANGED => {
"changed": true,
"checksum": "5d96d9ca1157ab35684544ebccb92587c735a7bf",
"dest": "/data/192.168.10.13/data/abc",
"md5sum": "3c96e5169486f07524a2e2fde1b74002",
"remote_checksum": "5d96d9ca1157ab35684544ebccb92587c735a7bf",
"remote_md5sum": null
}
-----------本地查看拉取的文件--------
[root@linux1 data]# ls
192.168.10.12 192.168.10.13 backup mysql57
[root@linux1 data]# cd 192.168.10.12/
[root@linux1 192.168.10.12]# ls
data
[root@linux1 192.168.10.12]# cd data/
[root@linux1 data]# ls
abc
[root@linux1 data]# cat abc
A B C D
7) 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 # 以哪个用户的身份执行
------------添加crontab定时任务-----------
[root@linux1 data]# ansible mysql -m cron -a 'name="mysql restart" minute=*/30 job="/etc/init.d/mysql.server restart &> /dev/null"'
192.168.10.13 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"envs": [],
"jobs": [
"mysql restart"
]
}
192.168.10.12 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"envs": [],
"jobs": [
"mysql restart"
]
}
-----------查看定时任务----------
[root@linux1 data]# ansible mysql -m shell -a 'crontab -l'
192.168.10.12 | CHANGED | rc=0 >>
#Ansible: mysql restart
*/30 * * * * /etc/init.d/mysql.server restart &> /dev/null
192.168.10.13 | CHANGED | rc=0 >>
#Ansible: mysql restart
*/30 * * * * /etc/init.d/mysql.server restart &> /dev/null
------------删除定时任务------
[root@linux1 data]# ansible mysql -m cron -a 'name="mysql restart" state=absent' #指定state=absent表示删除
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
[root@linux1 data]#
[root@linux1 data]# ansible mysql -m shell -a 'crontab -l' #删除后再次查看,发现已经删除
192.168.10.13 | CHANGED | rc=0 >>
192.168.10.12 | CHANGED | rc=0 >>
[root@linux1 data]#
8) yum 模块
该模块主要用于软件安装,选项如下:
name= #所安装的包的名称
state= #present—>安装, latest—>安装最新的, absent—> 卸载软件。
update_cache #强制更新yum的缓存
conf_file #指定远程yum安装时所依赖的配置文件(安装本地已有的包)。
disable_pgp_check #是否禁止GPG checking,只用于presentor latest。
disablerepo #临时禁止使用yum库。 只用于安装或更新时。
enablerepo #临时使用的yum库。只用于安装或更新时。
------------安装lrzsz软件包-------
[root@linux1 data]# ansible mysql -m yum -a 'name=lrzsz state=present'
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"lrzsz"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package lrzsz.x86_64 0:0.12.20-36.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n lrzsz x86_64 0.12.20-36.el7 server 78 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 78 k\nInstalled size: 181 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : lrzsz-0.12.20-36.el7.x86_64 1/1 \n Verifying : lrzsz-0.12.20-36.el7.x86_64 1/1 \n\nInstalled:\n lrzsz.x86_64 0:0.12.20-36.el7 \n\nComplete!\n"
]
}
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"lrzsz"
]
},
"msg": "Warning: RPMDB altered outside of yum.\n",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package lrzsz.x86_64 0:0.12.20-36.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n lrzsz x86_64 0.12.20-36.el7 server 78 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 78 k\nInstalled size: 181 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : lrzsz-0.12.20-36.el7.x86_64 1/1 \n Verifying : lrzsz-0.12.20-36.el7.x86_64 1/1 \n\nInstalled:\n lrzsz.x86_64 0:0.12.20-36.el7 \n\nComplete!\n"
]
}
----------安装完成后检查-------
[root@linux1 data]# ansible mysql -m shell -a 'rpm -qa|grep "lrzsz"'
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'. If you need to use command because yum, dnf or zypper 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.
192.168.10.12 | CHANGED | rc=0 >>
lrzsz-0.12.20-36.el7.x86_64
192.168.10.13 | CHANGED | rc=0 >>
lrzsz-0.12.20-36.el7.x86_64
----------卸载lrzsz软件包-------
[root@linux1 data]# ansible mysql -m yum -a 'name=lrzsz state=absent'
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"removed": [
"lrzsz"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package lrzsz.x86_64 0:0.12.20-36.el7 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nRemoving:\n lrzsz x86_64 0.12.20-36.el7 @server 181 k\n\nTransaction Summary\n================================================================================\nRemove 1 Package\n\nInstalled size: 181 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Erasing : lrzsz-0.12.20-36.el7.x86_64 1/1 \n Verifying : lrzsz-0.12.20-36.el7.x86_64 1/1 \n\nRemoved:\n lrzsz.x86_64 0:0.12.20-36.el7 \n\nComplete!\n"
]
}
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"removed": [
"lrzsz"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package lrzsz.x86_64 0:0.12.20-36.el7 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nRemoving:\n lrzsz x86_64 0.12.20-36.el7 @server 181 k\n\nTransaction Summary\n================================================================================\nRemove 1 Package\n\nInstalled size: 181 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Erasing : lrzsz-0.12.20-36.el7.x86_64 1/1 \n Verifying : lrzsz-0.12.20-36.el7.x86_64 1/1 \n\nRemoved:\n lrzsz.x86_64 0:0.12.20-36.el7 \n\nComplete!\n"
]
}
----------卸载完成后检查-------
[root@linux1 data]# ansible mysql -m shell -a 'rpm -qa|grep "lrzsz"'
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'. If you need to use command because yum, dnf or zypper 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.
192.168.10.12 | FAILED | rc=1 >>
non-zero return code
192.168.10.13 | FAILED | rc=1 >>
non-zero return code
9) service 模块
该模块主要用于程序服务管理,有如下主要选项:
arguments #命令行提供额外的参数
enabled #设置开机启动。
name= #服务名称
runlevel #开机启动的级别,一般不用指定。
sleep #在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。(定义在剧本中。)
state #有四种状态,分别为:started—>启动服务, stopped—>停止服务, restarted—>重启服务, reloaded—>重载
[root@linux1 data]# ansible mysql -m service -a 'name=mysql state=started enabled=true'
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": true,
"name": "mysql",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "remote-fs.target ypbind.service system.slice network-online.target systemd-journald.socket basic.target nscd.service ntpd.service xntpd.service ldap.service",
"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",
"CollectMode": "inactive",
"ConditionResult": "no",
"ConditionTimestampMonotonic": "0",
"Conflicts": "shutdown.target",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "LSB: start and stop MySQL",
"DevicePolicy": "auto",
"Documentation": "man:systemd-sysv-generator(8)",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "0",
"ExecMainStartTimestampMonotonic": "0",
"ExecMainStatus": "0",
"ExecReload": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql reload ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql start ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStop": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql stop ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"FailureAction": "none",
"FileDescriptorStoreMax": "0",
"FragmentPath": "/run/systemd/generator.late/mysql.service",
"GuessMainPID": "no",
"IOScheduling": "0",
"Id": "mysql.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "no",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestampMonotonic": "0",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "process",
"KillSignal": "15",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "3795",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "3795",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "0",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "mysql.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "none",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PermissionsStartOnly": "no",
"PrivateDevices": "no",
"PrivateNetwork": "no",
"PrivateTmp": "no",
"ProtectHome": "no",
"ProtectSystem": "no",
"RefuseManualStart": "no",
"RefuseManualStop": "no",
"RemainAfterExit": "yes",
"Requires": "system.slice basic.target",
"Restart": "no",
"RestartUSec": "100ms",
"Result": "success",
"RootDirectoryStartOnly": "no",
"RuntimeDirectoryMode": "0755",
"SameProcessGroup": "no",
"SecureBits": "0",
"SendSIGHUP": "no",
"SendSIGKILL": "yes",
"Slice": "system.slice",
"SourcePath": "/etc/rc.d/init.d/mysql",
"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": "5min",
"TimeoutStopUSec": "5min",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "forking",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "bad",
"Wants": "network-online.target",
"WatchdogTimestampMonotonic": "0",
"WatchdogUSec": "0"
}
}
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": true,
"name": "mysql",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "system.slice xntpd.service ntpd.service basic.target ypbind.service systemd-journald.socket network-online.target ldap.service remote-fs.target nscd.service",
"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",
"CollectMode": "inactive",
"ConditionResult": "no",
"ConditionTimestampMonotonic": "0",
"Conflicts": "shutdown.target",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "LSB: start and stop MySQL",
"DevicePolicy": "auto",
"Documentation": "man:systemd-sysv-generator(8)",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "0",
"ExecMainStartTimestampMonotonic": "0",
"ExecMainStatus": "0",
"ExecReload": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql reload ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql start ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStop": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql stop ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"FailureAction": "none",
"FileDescriptorStoreMax": "0",
"FragmentPath": "/run/systemd/generator.late/mysql.service",
"GuessMainPID": "no",
"IOScheduling": "0",
"Id": "mysql.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "no",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestampMonotonic": "0",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "process",
"KillSignal": "15",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "3795",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "3795",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "0",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "mysql.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "none",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PermissionsStartOnly": "no",
"PrivateDevices": "no",
"PrivateNetwork": "no",
"PrivateTmp": "no",
"ProtectHome": "no",
"ProtectSystem": "no",
"RefuseManualStart": "no",
"RefuseManualStop": "no",
"RemainAfterExit": "yes",
"Requires": "basic.target system.slice",
"Restart": "no",
"RestartUSec": "100ms",
"Result": "success",
"RootDirectoryStartOnly": "no",
"RuntimeDirectoryMode": "0755",
"SameProcessGroup": "no",
"SecureBits": "0",
"SendSIGHUP": "no",
"SendSIGKILL": "yes",
"Slice": "system.slice",
"SourcePath": "/etc/rc.d/init.d/mysql",
"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": "5min",
"TimeoutStopUSec": "5min",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "forking",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "bad",
"Wants": "network-online.target",
"WatchdogTimestampMonotonic": "0",
"WatchdogUSec": "0"
}
}
--------------检查是否启动--------
[root@linux1 data]# ansible mysql -m shell -a 'ps -ef |grep mysql'
192.168.10.12 | CHANGED | rc=0 >>
root 40911 1 0 00:18 ? 00:00:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/data/mysql57 --pid-file=/data/mysql57/linux2.pid
mysql 41270 40911 0 00:18 ? 00:00:00 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/data/mysql57 --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=error.log --pid-file=/data/mysql57/linux2.pid --socket=/tmp/mysql.sock --port=3306
root 41519 41518 0 00:19 pts/1 00:00:00 /bin/sh -c ps -ef |grep mysql
root 41521 41519 0 00:19 pts/1 00:00:00 grep mysql
192.168.10.13 | CHANGED | rc=0 >>
root 41979 1 0 05:57 ? 00:00:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/data/mysql57 --pid-file=/data/mysql57/linux3.pid
mysql 42338 41979 1 05:57 ? 00:00:00 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/data/mysql57 --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=error.log --pid-file=/data/mysql57/linux3.pid --socket=/tmp/mysql.sock --port=3306
root 42478 42473 0 05:58 pts/2 00:00:00 /bin/sh -c ps -ef |grep mysql
root 42480 42478 0 05:58 pts/2 00:00:00 grep mysql
[root@linux1 data]#
[root@linux1 data]# ansible mysql -m shell -a 'chkconfig'
192.168.10.12 | CHANGED | rc=0 >>
mysql 0:off 1:off 2:on 3:on 4:on 5:on 6:off
netconsole 0:off 1:off 2:off 3:off 4:off 5:off 6:off
network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
Note: This output shows SysV services only and does not include native
systemd services. SysV configuration data might be overridden by native
systemd configuration.
If you want to list systemd services use 'systemctl list-unit-files'.
To see services enabled on particular target use
'systemctl list-dependencies [target]'.
192.168.10.13 | CHANGED | rc=0 >>
mysql 0:off 1:off 2:on 3:on 4:on 5:on 6:off
netconsole 0:off 1:off 2:off 3:off 4:off 5:off 6:off
network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
Note: This output shows SysV services only and does not include native
systemd services. SysV configuration data might be overridden by native
systemd configuration.
If you want to list systemd services use 'systemctl list-unit-files'.
To see services enabled on particular target use
'systemctl list-dependencies [target]'.
[root@linux1 data]#
------------关闭服务--------
[root@linux1 data]# ansible mysql -m service -a 'name=mysql state=stopped enabled=false'
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": false,
"name": "mysql",
"state": "stopped",
"status": {
"ActiveEnterTimestamp": "Wed 2022-11-30 00:18:44 CST",
"ActiveEnterTimestampMonotonic": "20508364847",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "active",
"After": "xntpd.service basic.target system.slice network-online.target ypbind.service systemd-journald.socket remote-fs.target nscd.service ntpd.service ldap.service",
"AllowIsolate": "no",
"AmbientCapabilities": "0",
"AssertResult": "yes",
"AssertTimestamp": "Wed 2022-11-30 00:18:43 CST",
"AssertTimestampMonotonic": "20507291780",
"Before": "shutdown.target multi-user.target graphical.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",
"CollectMode": "inactive",
"ConditionResult": "yes",
"ConditionTimestamp": "Wed 2022-11-30 00:18:43 CST",
"ConditionTimestampMonotonic": "20507291780",
"Conflicts": "shutdown.target",
"ControlGroup": "/system.slice/mysql.service",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "LSB: start and stop MySQL",
"DevicePolicy": "auto",
"Documentation": "man:systemd-sysv-generator(8)",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "0",
"ExecMainStartTimestampMonotonic": "0",
"ExecMainStatus": "0",
"ExecReload": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql reload ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql start ; ignore_errors=no ; start_time=[Wed 2022-11-30 00:18:43 CST] ; stop_time=[Wed 2022-11-30 00:18:44 CST] ; pid=40903 ; code=exited ; status=0 }",
"ExecStop": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql stop ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"FailureAction": "none",
"FileDescriptorStoreMax": "0",
"FragmentPath": "/run/systemd/generator.late/mysql.service",
"GuessMainPID": "no",
"IOScheduling": "0",
"Id": "mysql.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "no",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestamp": "Wed 2022-11-30 00:18:43 CST",
"InactiveExitTimestampMonotonic": "20507292651",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "process",
"KillSignal": "15",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "3795",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "3795",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "0",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "mysql.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "none",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PermissionsStartOnly": "no",
"PrivateDevices": "no",
"PrivateNetwork": "no",
"PrivateTmp": "no",
"ProtectHome": "no",
"ProtectSystem": "no",
"RefuseManualStart": "no",
"RefuseManualStop": "no",
"RemainAfterExit": "yes",
"Requires": "system.slice basic.target",
"Restart": "no",
"RestartUSec": "100ms",
"Result": "success",
"RootDirectoryStartOnly": "no",
"RuntimeDirectoryMode": "0755",
"SameProcessGroup": "no",
"SecureBits": "0",
"SendSIGHUP": "no",
"SendSIGKILL": "yes",
"Slice": "system.slice",
"SourcePath": "/etc/rc.d/init.d/mysql",
"StandardError": "inherit",
"StandardInput": "null",
"StandardOutput": "journal",
"StartLimitAction": "none",
"StartLimitBurst": "5",
"StartLimitInterval": "10000000",
"StartupBlockIOWeight": "18446744073709551615",
"StartupCPUShares": "18446744073709551615",
"StatusErrno": "0",
"StopWhenUnneeded": "no",
"SubState": "running",
"SyslogLevelPrefix": "yes",
"SyslogPriority": "30",
"SystemCallErrorNumber": "0",
"TTYReset": "no",
"TTYVHangup": "no",
"TTYVTDisallocate": "no",
"TasksAccounting": "no",
"TasksCurrent": "38",
"TasksMax": "18446744073709551615",
"TimeoutStartUSec": "5min",
"TimeoutStopUSec": "5min",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "forking",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "bad",
"WantedBy": "multi-user.target graphical.target",
"Wants": "network-online.target",
"WatchdogTimestamp": "Wed 2022-11-30 00:18:44 CST",
"WatchdogTimestampMonotonic": "20508364798",
"WatchdogUSec": "0"
}
}
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": false,
"name": "mysql",
"state": "stopped",
"status": {
"ActiveEnterTimestamp": "Wed 2022-11-30 05:57:50 CST",
"ActiveEnterTimestampMonotonic": "20506796934",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "active",
"After": "ntpd.service nscd.service systemd-journald.socket system.slice ldap.service basic.target ypbind.service xntpd.service remote-fs.target network-online.target",
"AllowIsolate": "no",
"AmbientCapabilities": "0",
"AssertResult": "yes",
"AssertTimestamp": "Wed 2022-11-30 05:57:48 CST",
"AssertTimestampMonotonic": "20504591457",
"Before": "shutdown.target multi-user.target graphical.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",
"CollectMode": "inactive",
"ConditionResult": "yes",
"ConditionTimestamp": "Wed 2022-11-30 05:57:48 CST",
"ConditionTimestampMonotonic": "20504591457",
"Conflicts": "shutdown.target",
"ControlGroup": "/system.slice/mysql.service",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "LSB: start and stop MySQL",
"DevicePolicy": "auto",
"Documentation": "man:systemd-sysv-generator(8)",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "0",
"ExecMainStartTimestampMonotonic": "0",
"ExecMainStatus": "0",
"ExecReload": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql reload ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql start ; ignore_errors=no ; start_time=[Wed 2022-11-30 05:57:48 CST] ; stop_time=[Wed 2022-11-30 05:57:50 CST] ; pid=41971 ; code=exited ; status=0 }",
"ExecStop": "{ path=/etc/rc.d/init.d/mysql ; argv[]=/etc/rc.d/init.d/mysql stop ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"FailureAction": "none",
"FileDescriptorStoreMax": "0",
"FragmentPath": "/run/systemd/generator.late/mysql.service",
"GuessMainPID": "no",
"IOScheduling": "0",
"Id": "mysql.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "no",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestamp": "Wed 2022-11-30 05:57:48 CST",
"InactiveExitTimestampMonotonic": "20504593165",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "process",
"KillSignal": "15",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "3795",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "3795",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "0",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "mysql.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "none",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PermissionsStartOnly": "no",
"PrivateDevices": "no",
"PrivateNetwork": "no",
"PrivateTmp": "no",
"ProtectHome": "no",
"ProtectSystem": "no",
"RefuseManualStart": "no",
"RefuseManualStop": "no",
"RemainAfterExit": "yes",
"Requires": "system.slice basic.target",
"Restart": "no",
"RestartUSec": "100ms",
"Result": "success",
"RootDirectoryStartOnly": "no",
"RuntimeDirectoryMode": "0755",
"SameProcessGroup": "no",
"SecureBits": "0",
"SendSIGHUP": "no",
"SendSIGKILL": "yes",
"Slice": "system.slice",
"SourcePath": "/etc/rc.d/init.d/mysql",
"StandardError": "inherit",
"StandardInput": "null",
"StandardOutput": "journal",
"StartLimitAction": "none",
"StartLimitBurst": "5",
"StartLimitInterval": "10000000",
"StartupBlockIOWeight": "18446744073709551615",
"StartupCPUShares": "18446744073709551615",
"StatusErrno": "0",
"StopWhenUnneeded": "no",
"SubState": "running",
"SyslogLevelPrefix": "yes",
"SyslogPriority": "30",
"SystemCallErrorNumber": "0",
"TTYReset": "no",
"TTYVHangup": "no",
"TTYVTDisallocate": "no",
"TasksAccounting": "no",
"TasksCurrent": "29",
"TasksMax": "18446744073709551615",
"TimeoutStartUSec": "5min",
"TimeoutStopUSec": "5min",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "forking",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "bad",
"WantedBy": "graphical.target multi-user.target",
"Wants": "network-online.target",
"WatchdogTimestamp": "Wed 2022-11-30 05:57:50 CST",
"WatchdogTimestampMonotonic": "20506796897",
"WatchdogUSec": "0"
}
}
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
[root@linux1 data]# ansible mysql -m user -a 'name=aaa uid=8888' #创建用户
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 8888,
"home": "/home/aaa",
"name": "aaa",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 8888
}
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 8888,
"home": "/home/aaa",
"name": "aaa",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 8888
}
[root@linux1 data]#
[root@linux1 data]# ansible mysql -m shell -a 'id aaa' # 查看用户是否创建成功
192.168.10.13 | CHANGED | rc=0 >>
uid=8888(aaa) gid=8888(aaa) groups=8888(aaa)
192.168.10.12 | CHANGED | rc=0 >>
uid=8888(aaa) gid=8888(aaa) groups=8888(aaa)
[root@linux1 data]#
[root@linux1 data]# ansible mysql -m user -a 'name=aaa state=absent' # 删除用户
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"force": false,
"name": "aaa",
"remove": false,
"state": "absent"
}
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"force": false,
"name": "aaa",
"remove": false,
"state": "absent"
}
[root@linux1 data]#
[root@linux1 data]#
[root@linux1 data]# ansible mysql -m shell -a 'id aaa' #再次查看用户是否存在
192.168.10.13 | FAILED | rc=1 >>
id: aaa: no such usernon-zero return code
192.168.10.12 | FAILED | rc=1 >>
id: aaa: no such usernon-zero return code
[root@linux1 data]#
11) group 模块
该模块主要用于添加或者删除组,选项如下:
gid= #设置组的GID号
name= #指定组的名称
state= #指定组的状态,默认为创建,设置值为absent为删除
system= #设置值为yes,表示创建为系统组
[root@linux1 data]# ansible mysql -m group -a 'name=abc gid=8888' #创建组
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 8888,
"name": "abc",
"state": "present",
"system": false
}
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 8888,
"name": "abc",
"state": "present",
"system": false
}
[root@linux1 data]# ansible mysql -m shell -a 'cat /etc/group | grep 8888' #查看组
192.168.10.13 | CHANGED | rc=0 >>
abc:x:8888:
192.168.10.12 | CHANGED | rc=0 >>
abc:x:8888:
[root@linux1 data]# ansible mysql -m group -a 'name=abc state=absent' #删除组
192.168.10.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "abc",
"state": "absent"
}
192.168.10.13 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "abc",
"state": "absent"
}
[root@linux1 data]#
[root@linux1 data]# ansible mysql -m shell -a 'cat /etc/group | grep 8888' #查看组
192.168.10.13 | FAILED | rc=1 >>
non-zero return code
192.168.10.12 | FAILED | rc=1 >>
non-zero return code
[root@linux1 data]#
12) script 模块
该模块用于将本机的脚本在被管理端的机器上运行,直接指定脚本路径即可
------------找到一个脚本文件----------
[root@linux1 ~]# cat /tmp/df.sh
#!/bin/bash
date >> /tmp/disk_total.log
df -hl >> /tmp/disk_total.log
------------执行本地脚本文件----------
[root@linux1 ~]# ansible mysql -m script -a '/tmp/df.sh'
192.168.10.12 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.10.12 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.10.12 closed."
],
"stdout": "",
"stdout_lines": []
}
192.168.10.13 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.10.13 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.10.13 closed."
],
"stdout": "",
"stdout_lines": []
}
---------------查看脚本执行结果---------
[root@linux1 ~]# ansible mysql -m shell -a 'cat /tmp/disk_total.log'
192.168.10.13 | CHANGED | rc=0 >>
Wed Nov 30 06:16:17 CST 2022
Filesystem Size Used Avail Use% Mounted on
devtmpfs 475M 0 475M 0% /dev
tmpfs 487M 0 487M 0% /dev/shm
tmpfs 487M 14M 473M 3% /run
tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/mapper/centos-root 50G 12G 39G 23% /
/dev/mapper/centos-home 47G 33M 47G 1% /home
/dev/sda1 1014M 152M 863M 15% /boot
tmpfs 98M 0 98M 0% /run/user/0
/dev/sr0 9.5G 9.5G 0 100% /mnt
192.168.10.12 | CHANGED | rc=0 >>
Wed Nov 30 00:37:13 CST 2022
Filesystem Size Used Avail Use% Mounted on
devtmpfs 475M 0 475M 0% /dev
tmpfs 487M 0 487M 0% /dev/shm
tmpfs 487M 7.7M 479M 2% /run
tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/mapper/centos-root 46G 10G 36G 22% /
/dev/sda1 197M 130M 68M 66% /boot
tmpfs 98M 0 98M 0% /run/user/0
/dev/sr0 9.5G 9.5G 0 100% /mnt
[root@linux1 ~]#
13) setup 模块
该模块主要用于收集信息,是通过调用facts组件来实现的。facts组件是Ansible用于采集被管机器设备信息的一个功能,我们可以使用setup模块查机器的所有facts信息,可以使用filter来查看指定信息。整个facts信息被包装在一个JSON格式的数据结构中,ansible_facts是最上层的值。facts就是变量,内建变量 。每个主机的各种信息,cpu颗数、内存大小等。会存在facts中的某个变量中。调用后返回很多对应主机的信息,在后面的操作中可以根据不同的信息来做不同的操作。如redhat系列用yum安装,而debian系列用apt来安装软件。
---------------查看内内存---------
[root@linux1 ~]# ansible mysql -m setup -a 'filter="*mem*"'
192.168.10.12 | SUCCESS => {
"ansible_facts": {
"ansible_memfree_mb": 473,
"ansible_memory_mb": {
"nocache": {
"free": 753,
"used": 219
},
"real": {
"free": 473,
"total": 972,
"used": 499
},
"swap": {
"cached": 0,
"free": 3999,
"total": 3999,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.10.13 | SUCCESS => {
"ansible_facts": {
"ansible_memfree_mb": 244,
"ansible_memory_mb": {
"nocache": {
"free": 550,
"used": 422
},
"real": {
"free": 244,
"total": 972,
"used": 728
},
"swap": {
"cached": 0,
"free": 2047,
"total": 2047,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
--------------查看CPU-------
[root@linux1 ~]# ansible mysql -m setup -a 'filter="*cpu*"'
192.168.10.13 | SUCCESS => {
"ansible_facts": {
"ansible_processor_vcpus": 1,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.10.12 | SUCCESS => {
"ansible_facts": {
"ansible_processor_vcpus": 1,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
-------------将查询的信息保存在本地主机-------------------
[root@linux1 ~]# ansible mysql -m setup -a 'filter="*mem*"' --tree /tmp/memory
192.168.10.13 | SUCCESS => {
"ansible_facts": {
"ansible_memfree_mb": 239,
"ansible_memory_mb": {
"nocache": {
"free": 549,
"used": 423
},
"real": {
"free": 239,
"total": 972,
"used": 733
},
"swap": {
"cached": 0,
"free": 2047,
"total": 2047,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.10.12 | SUCCESS => {
"ansible_facts": {
"ansible_memfree_mb": 473,
"ansible_memory_mb": {
"nocache": {
"free": 753,
"used": 219
},
"real": {
"free": 473,
"total": 972,
"used": 499
},
"swap": {
"cached": 0,
"free": 3999,
"total": 3999,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}