欢迎光临散文网 会员登陆 & 注册

3.ansible命令的常用模块使用-ad-hoc模式-批量操作实战

2023-06-14 23:10 作者:运维实战课程  | 我要投稿

1.ansible的ad-hoc模式或命令模式简介
ansible在命令行中执行的命令,也称为ad-hoc模式,ad-hoc模式其实就是"临时命令",执行完即结束,不会保存。
用ansible命令模式批量管理主机,对复杂的不方便,需要使用playbook剧本模式。

2.ansible常用的模块
1).前提准备:
a).规划被管理主机列表,如下:
[root@localhost ~]# cat /etc/ansible/hosts
……
[test]                           #添加一个组名
192.168.171.129           #添加被管理主机的IP
192.168.171.130           #添加被管理主机的IP

b).安装ansible
[root@localhost ~]# yum -y install epel-release        #先安装epel-release
[root@localhost ~]# yum -y install ansible
[root@localhost ~]# ansible --version
ansible 2.9.27

c).修改ansible的配置文件
[root@localhost ~]# vim /etc/ansible/ansible.cfg
……
host_key_checking = False        #禁用每次执行ansbile命令检查ssh key host ,默认注释,开启即可
                                              #首次连接是否需要检查key认证,建议放开注释设为False
log_path = /var/log/ansible.log   #开启日志记录, 默认注释,开启即可
……
[accelerate]
accelerate_port = 5099             #加速连接端口,释放,默认注释,也可改变端口号,此处没改
#accelerate_timeout = 30
#accelerate_connect_timeout = 5.0
# The daemon timeout is measured in minutes. This time is measured
# from the last activity to the accelerate daemon.
#accelerate_daemon_timeout = 30
# If set to yes, accelerate_multi_key will allow multiple
# private keys to be uploaded to it, though each user must
# have access to the system via SSH to add a new key. The default
# is "no".
accelerate_multi_key = yes      #释放,默认注释

d).配置管理端到被管理端的免密登录,以方便ansible进行管理
管理端机器上生成ssh密钥对,实现能无密码连接登录到被管理机器:
[root@localhost ~]# ssh-keygen -t rsa  #下面一路回车,不用输密码
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
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:rZn0m2eUdeYzqZUEYE2W8cAZJ2ElF/6/XvvP7aoq7EQ root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|           o=@B=.|
|          . o*O  |
|              .o |
|         .    ..+|
|        E .  o.++|
|       o =  o  *o|
|       .= ..  o =|
|       .o  oo. .=|
|       ...++..o*O|
+----[SHA256]-----+
[root@localhost ~]# ls /root/.ssh/
id_rsa  id_rsa.pub
[root@localhost ~]# yum  -y install openssh openssh-clients openssh-server #若没有ssh命令和ssh-copy-id等时候的安装
[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.171.129 #或仅IP也可
#第一次需要输入对方用户密码:123456
[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.171.130 #或仅IP也可
#第一次需要输入对方用户密码:123456
[root@localhost ~]# ssh root@192.168.171.129 ifconfig |head -3
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
       inet 192.168.171.129  netmask 255.255.255.0  broadcast 192.168.171.255
       inet6 fe80::2fab:326:734f:2936  prefixlen 64  scopeid 0x20<link>
[root@localhost ~]# ssh root@192.168.171.130 ifconfig |head -3
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
       inet 192.168.171.130  netmask 255.255.255.0  broadcast 192.168.171.255
       inet6 fe80::eaa2:384e:60ac:87b1  prefixlen 64  scopeid 0x20<link>


2).ansible的常用模块使用-通过ad-hoc命令行使用
1).command或shell模块,执行远程命令,管理被管理端 (ad-hoc模式,其实就是临时命令,执行完即结束,不会保存)
(都是批量执行命令,shell更强大,什么都能干,如果需要一些管道等复杂命令的操作,则使用shell,command完成不了,shell还能执行脚本)
执行远程命令: 以下的command也可以用shell代替
# ansible 列表组名 -m command/shell -a "执行的远程命令"   #管理单独某个模块组名下机器,执行远程机器命令
# ansible all -m command -a "执行的远程命令"                       #管理所有模块下机器,执行远程机器命令
# ansible test -m command -a "ifconfig|grep ens33" -f 50          #command执行不了,-f 50一次显示50个主机
# ansible test -m shell -a "ifconfig|grep ens33" -f 50                 #shell可以执行,-f 50一次显示50个主机
192.168.171.130 | CHANGED | rc=0 >>
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
192.168.171.129 | CHANGED | rc=0 >>
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
其他例子:
[root@localhost ~]# ansible test -m command -a "free -m"
192.168.171.129 | CHANGED | rc=0 >>
             total        used        free      shared  buff/cache   available
Mem:            984         124         498           6         361         674
Swap:          2047           0        2047
192.168.171.130 | CHANGED | rc=0 >>
             total        used        free      shared  buff/cache   available
Mem:            984         123         500           6         359         676
Swap:          2047           0        2047
[root@localhost ~]# ansible test -m shell -a "free -m"
192.168.171.130 | CHANGED | rc=0 >>
             total        used        free      shared  buff/cache   available
Mem:            984         123         500           6         359         676
Swap:          2047           0        2047
192.168.171.129 | CHANGED | rc=0 >>
             total        used        free      shared  buff/cache   available
Mem:            984         124         499           6         361         674
Swap:          2047           0        2047
[root@localhost ~]# ansible test -m shell -a "sh /root/a.sh"
192.168.171.129 | CHANGED | rc=0 >>
129

192.168.171.130 | CHANGED | rc=0 >>
130

2).copy模块,批量发送文件到被管理端或向被管理端文件写内容
copy模块下常用参数:
src:        推送数据的源文件信息
dest:       推送数据的目录路径
backup:   对推送传送过去的文件,进行原文件备份,再接收新文件
content:   直接批量在被管理端文件中添加内容
group:     将本地文件推送到远端,指定文件属组信息
owner:     将本地文件推送到远端,指定文件属主信息
mode:      将本地文件推动到远端,指定文件权限信息
(1).将管理端(ansible机器)上本地文件(/tmp/a.txt)批量发送给被管理端(/tmp/目录):
copy模块注意:所有被管理端需要安装:libselinux-python ,此处为192.168.171.129和192.168.171.130上)
[root@localhost ~]# yum install libselinux-python -y  默认cent7.x已经安装,若没有安装,需要先安装该包
a)批量发送文件:
管理端:
[root@localhost ~]# cat /tmp/a.txt
111
[root@localhost ~]# ansible test -m copy -a "src=/tmp/a.txt dest=/tmp/"
192.168.171.129 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   },
   "changed": true,
   "checksum": "63bea2e3b0c7cd2d1f98bc5b7a9951eafcfead0f",
   "dest": "/tmp/a.txt",
   "gid": 0,
   "group": "root",
   "md5sum": "1181c1834012245d785120e3505ed169",
   "mode": "0644",
   "owner": "root",
   "secontext": "unconfined_u:object_r:admin_home_t:s0",
   "size": 4,
   "src": "/root/.ansible/tmp/ansible-tmp-1570087134.72-175986676314669/source",
   "state": "file",
   "uid": 0
}
192.168.171.130 | CHANGED => {
   "ansible_facts": {
       "discovered_interpreter_python": "/usr/bin/python"
   },
   "changed": true,
   "checksum": "63bea2e3b0c7cd2d1f98bc5b7a9951eafcfead0f",
   "dest": "/tmp/a.txt",
   "gid": 0,
   "group": "root",
   "md5sum": "1181c1834012245d785120e3505ed169",
   "mode": "0644",
   "owner": "root",
   "secontext": "unconfined_u:object_r:admin_home_t:s0",
   "size": 4,
   "src": "/root/.ansible/tmp/ansible-tmp-1570087134.73-59570214580082/source",
   "state": "file",
   "uid": 0
}
被管理端:  (所有被管理端需要安装:libselinux-python ,此处为192.168.171.129和192.168.171.130上)
[root@localhost ~]# yum install libselinux-python -y  
[root@localhost ~]# ls /tmp/   #被管理端192.168.171.129,需要yum -y install libselinux-python
a.txt
[root@localhost ~]# cat /tmp/a.txt
111
[root@localhost ~]# ls /tmp/   #被管理端192.168.171.130,需要yum -y install libselinux-python
a.txt  yum.log
[root@localhost ~]# cat /tmp/a.txt
111

(2).批量将内容写入远端文件:(远端文件可事先不存在)直接向远端文件内写入数据信息,并且会覆盖远端文件内容原有数据信息
管理端:   content定义要写的内容, dest:定义要写入远端的文件名
[root@localhost ~]# ansible test -m copy -a "content='123' dest=/etc/rsync.pass owner=root group=root mode=600"
被管理端:
[root@localhost ~]# cat /etc/rsync.pass  #被管理端171.129和171.130上
123[root@localhost ~]#

3).yum模块,批量安装软件(相当于到远端机器执行yum -y install xxx)
格式: # ansible test -m yum -a "name=要安装的服务名 state=installed"
例子:如:ansible test -m yum -a "name=httpd state=installed"
使用详解:
name:  指定要安装的软件包名称
name的常用参数:即是常用软件包的名称,如:httpd,....
state:   指定使用yum的方法进行安装,卸载等操作
state的常用参数如下:
installed,present       安装软件包
removed,absent        移除软件包
latest                      安装最新软件包
例子:
管理端:
[root@localhost ~]# ansible test -m yum -a "name=httpd state=installed"
[root@localhost ~]# ansible test -m command -a "systemctl start httpd"
所有被管理端:
#httpd服务已经安装完成
[root@localhost ~]# systemctl status httpd
 httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
  Active: active (running) since Thu 2019-10-03 16:05:38 CST; 15s ago
4).service模块,启动,停止,重启,重载服务等
格式: # ansible test -m service -a "name=服务名 state=stopped enabled=yes"
例子:如: ansible test -m service -a "name=httpd state=stopped enabled=yes"
使用详解:
name:  定义要启动服务的名称,参数即为各服务名
state: 指定服务状态是停止或运行,或重载等,参数如下:
   started:     启动
   stopped:     停止
   restarted    重启
   reloaded     重载
enabled: 是否让服务开机自启动
例子:
管理端:
[root@localhost ~]# ansible test -m command -a "systemctl status httpd"
192.168.171.129 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
  Active: active (running) since Thu 2019-10-03 16:05:38 CST; 22min ago
    Docs: man:httpd(8)
......
192.168.171.130 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
  Active: active (running) since Thu 2019-10-03 16:05:38 CST; 22min ago
    Docs: man:httpd(8)
......
[root@localhost ~]# ansible test -m service -a "name=httpd state=stopped enabled=yes"
[root@localhost ~]# ansible test -m command -a "systemctl status httpd"
192.168.171.129 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
  Active: inactive (dead) since Thu 2019-10-03 16:30:41 CST; 41s ago
.......
192.168.171.130 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
  Active: inactive (dead) since Thu 2019-10-03 16:30:41 CST; 41s ago
........
所有被管理端:
[root@localhost ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
  Active: inactive (dead) since Thu 2019-10-03 16:30:41 CST; 1min 5s ago

5).script模块,编写脚本和执行脚本(本地编写脚本,本地运行,即可等同于在远程执行)
在本地运行模块,等同于在远程执行,不需要将脚本文件进行推送目标主机执行。
格式:# ansible test -m script -a "/.../本地编写的脚本.sh"
例子:
管理端:
[root@localhost ~]# cat /root/yum_wget.sh
#!/usr/bin/bash
yum -y install wget
[root@localhost ~]# chmod +x /root/yum_wget.sh
[root@localhost ~]# ansible test -m script -a "/root/yum_wget.sh"
所有被管理端:
[root@localhost ~]# wget -V
GNU Wget 1.14 built on linux-gnu.
6).file模块,配置模块,远程创建目录,远程创建文件,远程做软硬链接文件
远程创建目录:
# ansible test -m file -a "path=/tmp/shi state=directory"    
远程创建文件:
# ansible test -m file -a "path=/tmp/shi.txt state=touch mode=555 owner=root group=root"
远程做软连接:
# ansible test -m file -a "src=/tmp/shi.txt path=/tmp/shi.txt_link state=link"
递归创建或更改目录权限:
# ansible test -m file -a "path=/tmp/shi state=directory owner=root group=root mode=600 recurse=yes"
path:     指定远程主机目录或文件目录
recurse:   递归授权
state:    
 directory:    在远端创建mull
 touch:        在远端创建文件
 link:         link或hard表示创建链接文件
 absent:       表示删除文件或目录
 mode:         设置文件或目录权限
 owner:        设置文件或目录属主信息
 group:        设置文件或目录属组信息
例子:
管理端:
[root@localhost ~]# ansible test -m file -a "path=/tmp/shi state=directory" #远程创建目录 
所有被管理端:
目录/tmp/shi目录会被创建出来。
管理端:
[root@localhost ~]# ansible test -m file -a "path=/tmp/shi.txt state=touch mode=555 owner=root group=root"
所有被管理端:
文件:/tmp/shi.txt文件会被创建出来,且权限为555
管理端:
[root@localhost ~]# ansible test -m file -a "src=/tmp/shi.txt path=/tmp/shi.txt_link state=link"
所有被管理端:
文件:/tmp/shi.txt文件会被创建软连接,软连接文件为:/tmp/shi.txt_link
管理端:
[root@localhost ~]# ansible test -m file -a "path=/tmp/shi state=directory owner=root group=root mode=600 recurse=yes"
所有被管理端:
[root@localhost ~]# ll /tmp/shi/a.txt
-rw-------. 1 root root 4 Oct  3 17:29 /tmp/shi/a.txt
7).group模块,远程创建组
格式: # ansible test -m group -a "name=要创建的组名 gid=888 state=present"  #创建组,指定gid
例子,如:
[root@localhost ~]# ansible test -m group -a "name=shi_group gid=888 state=present"
name:   指定创建的组名
gid:    指定组的gid
state:  表示对组的操作状态,参数如下:
 absent:   删除远端的组
 present: 创建远端的组(默认)
例子:
管理端:
[root@localhost ~]# ansible test -m group -a "name=shi_group gid=888 state=present"
被管理端:
[root@localhost ~]# tail -2 /etc/group
apache:x:48:
shi_group:x:888:

8).user模块,远程创建用户
创建用户:不加密码:
# ansible test -m user -a "name=shi uid=88 group=shi_group shell=/sbin/nologin create_home=no state=present"  
删除用户:
# ansible test -m user -a "name=shi uid=88 group=shi_group shell=/sbin/nologin create_home=no state=absent"
创建普通用户并设置登录密码:
# echo 'mima' |openssl passwd -1 -stdin  #给指定的密码内容加密,注意需要加密,用户才能登录
$1$PxrQduFH$0sqImb.R6gy80gm8qlUvc0
# ansible test -m user -a 'name=shi3 password="$1$PxrQduFH$0sqImb.R6gy80gm8qlUvc0"'
name:   指定创建的用户名
uid:         指定用户的uid
gruop:       指定用户组名称
gruops:      指定附加组名称
password:    给用户添加密码
shell:       指定用户登录shell
create_home: 是否创建家目录
state:       表示对用户的操作状态,参数如下:
     absent:   删除远端的组
     present: 创建远端的组(默认)
例子:管理端:
# ansible test -m user -a "name=shi uid=88 group=shi_group shell=/sbin/nologin create_home=no state=present"  #创建不加密码
所有被管理端即可创建用户shi:
[root@localhost ~]# id shi
uid=88(shi) gid=888(shi_group) groups=888(shi_group)
创建普通用户并设置登录密码:
管理端:
[root@localhost ~]# echo 'mima' |openssl passwd -1 -stdin  #给指定的密码内容加密,注意需要加密,用户才能登录
$1$PxrQduFH$0sqImb.R6gy80gm8qlUvc0
[root@localhost ~]# ansible test -m user -a 'name=shi3 password="$1$PxrQduFH$0sqImb.R6gy80gm8qlUvc0"'
[root@localhost ~]# ssh shi3@192.168.171.129
shi3@192.168.171.129's password:
[shi3@localhost ~]$ ifconfig |head -2
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
       inet 192.168.171.129  netmask 255.255.255.0  broadcast 192.168.171.255
所有被管理端有用户shi3且能登录,如下:
[root@localhost ~]# id shi3
uid=1001(shi3) gid=1001(shi3) groups=1001(shi3)

9).cron模块,远程添加定时任务  (下面:a.sh是远程机器上本地有的脚本)
远程添加定时任务,未设置注释信息:
# ansible test -m cron -a "minute=00 hour=01 day=* month=* weekday=* job='/bin/sh /root/a.sh' state=present"
远程添加定时任务,并设置注释信息,防止定时任务重复:
# ansible test -m cron -a "minute=00 hour=01 day=* month=* weekday=* name='注释信息' job='/bin/sh /root/a.sh' state=present"
远程注释定时任务:
# ansible test -m cron -a "minute=00 hour=01 day=* month=* weekday=* name='cron1' job='/bin/sh /root/a.sh' state=present disabled=yes"
远程删除定时任务:
# ansible test -m cron -a "minute=00 hour=01 day=* month=* weekday=* name='cron1' job='/bin/sh /root/a.sh' state=absent"
例子:
管理端:
[root@localhost ~]# ansible test -m cron -a "minute=00 hour=01 day=* month=* weekday=* job='/bin/sh /root/a.sh' state=present"         #远程添加定时任务,未设置注释信息
所有被管理端:
[root@localhost ~]# crontab -l
#Ansible: None
00 01 * * * /bin/sh /root/a.sh
管理端:
[root@localhost ~]# ansible test -m cron -a "minute=00 hour=01 day=* month=* weekday=* name='cron1' job='/bin/sh /root/a.sh' state=present"    #远程添加定时任务,并设置注释信息,防止定时任务重复  
所有被管理端:
[root@localhost ~]# crontab -l
#Ansible: cron1
00 01 * * * /bin/sh /root/a.sh
管理端:
[root@localhost ~]# ansible test -m cron -a "minute=00 hour=01 day=* month=* weekday=* name='cron1' job='/bin/sh /root/a.sh' state=present disabled=yes"  #远程注释定时任务
所有被管理端:
[root@localhost ~]# crontab -l
#Ansible: cron1
#00 01 * * * /bin/sh /root/a.sh
管理端:
[root@localhost ~]# ansible test -m cron -a "minute=00 hour=01 day=* month=* weekday=* name='cron1' job='/bin/sh /root/a.sh' state=absent"   #远程删除定时任务
所有被管理端:
[root@localhost ~]# crontab -l

10).mount模块,远程添加挂载
立刻挂载并写入/etc/fstab中:
# ansible test -m mount -a "src=192.168.171.128:/data path=/opt fstype=nfs opts=defaults,noatime state=mounted"
立刻卸载并清除/etc/fstab中信息:
# ansible test -m mount -a "src=192.168.171.128:/data path=/opt fstype=nfs opts=defaults,noatime state=absent"
src:     要被挂载的原目录
path:    要挂载到的本地目录
fstype:  要挂载的文件类型
state:   挂载或卸载的状态,常用参数如下:
  present:        开机挂载,不会直接挂载设备,仅将配置写入/etc/fstab,不会马上挂载
  mounted:        马上直接挂载设备,并将配置写入/etc/fstab
  unmounted:      马上直接卸载设备,不会清除/etc/fstab写入的配置
  absent:         马上直接卸载设备,会清理/etc/fstab写入的配置
例子:
管理端:192.168.171.128
[root@localhost ~]# yum -y install nfs-utils    #被管理的挂载端也要安装,才能挂载
[root@localhost ~]# vim /etc/exports
/data *(rw,no_root_squash)
[root@localhost ~]# systemctl start nfs
[root@localhost ~]# ansible test -m mount -a "src=192.168.171.128:/data path=/opt fstype=nfs opts=defaults,noatime state=mounted"  
所有被管理端:
[root@localhost ~]# mount |grep opt
192.168.171.128:/data on /opt type nfs4 (rw,noatime,vers=4.1,rsize=131072,wsize=131072,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.171.129,local_lock=none,addr=192.168.171.128)
[root@localhost ~]# tail -1 /etc/fstab
192.168.171.128:/data /opt nfs defaults,noatime 0 0
管理端:192.168.171.128
[root@localhost ~]# ansible test -m mount -a "src=192.168.171.128:/data path=/opt fstype=nfs opts=defaults,noatime state=absent"
被管理端:
[root@localhost ~]# mount |grep opt

[root@localhost ~]# tail -2 /etc/fstab
/dev/mapper/centos-home /home                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0

11).get_url模块,下载模块
下载模块:get_url
 get_url:
   url: 下载地址
   dest: 下载到本地的路径;
   mode: 权限;
checksum:对资源做校验;
sha256:
    md5:
例子:
管理端:192.168.171.128
[root@localhost ~]# ansible test -m get_url -a 'url=http://rpms.famillecollet.com/enterprise/remi-release-6.rpm dest=/tmp mode=0666'
被管理端:192.168.171.129 192.168.171.130
[root@localhost ~]# ls /tmp/          #查看被下载到/tmp/目录中且权限666
remi-release-6.rpm
[root@localhost ~]# ll /tmp/remi-release-6.rpm
-rw-rw-rw- 1 root root 20124 Apr 10 00:13 /tmp/remi-release-6.rpm

12).systemd模块,通过systemd来管理服务启停,类似systemctl start httpd
解释:
name 服务名称
state 服务状态
started 启动
stopped 停止
restarted 重启
reloaded 重载
enabled 开启自启动|  yes 启   no 不
daemon_reload: yes       重载systemd整个的配置文件
例子:用systemd模块启动或停止服务,加入开机自启动或关闭开机自启
管理端:192.168.171.128
[root@localhost ~]# ansible test -m command -a 'yum -y install httpd'   #先用别的命令,远程批量安装httpd
[root@localhost ~]# ansible test -m command -a 'systemctl status httpd' #查看,刚安装的服务并未启动
192.168.171.129 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
  Active: inactive (dead)
    Docs: man:httpd(8)
          man:apachectl(8)non-zero return code
192.168.171.130 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
  Active: inactive (dead)
    Docs: man:httpd(8)
          man:apachectl(8)non-zero return code
a).用systemd模块启动服务并加入开机自启动:
[root@localhost ~]# ansible test -m systemd -a 'name=httpd state=started enabled=yes'
[root@localhost ~]# ansible test -m command -a 'systemctl status httpd' #查看,刚安装的服务已经启动
192.168.171.129 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
 Active: active (running) since Mon 2023-04-10 00:24:21 CST; 1min 27s ago
.....
192.168.171.130 | CHANGED | rc=0 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
  Active: active (running) since Mon 2023-04-10 00:24:21 CST; 1min 27s ago
...
b).用systemd模块停止服务,并关闭开机自启动:
[root@localhost ~]# ansible test -m systemd -a 'name=httpd state=stopped enabled=no'
[root@localhost ~]# ansible test -m command -a 'systemctl status httpd' #查看被管理端服务已经停止
192.168.171.129 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
  Active: inactive (dead)
...
192.168.171.130 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
  Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
  Active: inactive (dead)
...

13).selinux模块,控制selinux开启或关闭
- name: Enable SELinux
 selinux:
   policy: targeted
   state: disabled
管理端:192.168.171.128
[root@localhost ~]# ansible test -m command -a 'getenforce'   #先远程查看被管理端selinux是开着的
192.168.171.129 | CHANGED | rc=0 >>
Enforcing
192.168.171.130 | CHANGED | rc=0 >>
Enforcing
[root@localhost ~]# ansible test -m selinux -a 'state=disabled'   #远程关闭被管理端selinux
[root@localhost ~]# ansible test -m command -a 'getenforce'   #再远程查看被管理端selinux是已经关闭
192.168.171.130 | CHANGED | rc=0 >>
Permissive
192.168.171.129 | CHANGED | rc=0 >>
Permissive
被管理端:192.168.171.129 192.168.171.130
[root@localhost ~]# getenforce
Permissive

14).setup模块,主机信息模块,获取主机的信息
[root@localhost ~]# ansible test -m setup       #获取主机所有的信息
192.168.171.130 | SUCCESS => {
   "ansible_facts": {
       "ansible_all_ipv4_addresses": [
           "192.168.171.130"
       ],
       },
....
192.168.171.129 | SUCCESS => {
   "ansible_facts": {
       "ansible_all_ipv4_addresses": [
           "192.168.171.129"
       ],  
       },
....
[root@localhost ~]# ansible test -m setup -a 'filter=ansible_default_ipv4'  #获取ip信息
192.168.171.129 | SUCCESS => {
   "ansible_facts": {
       "ansible_default_ipv4": {
           "address": "192.168.171.129",
           "alias": "ens33",
           "broadcast": "192.168.171.255",
           "gateway": "192.168.171.2",
           "interface": "ens33",
           "macaddress": "00:0c:29:12:47:83",
           "mtu": 1500,
           "netmask": "255.255.255.0",
           "network": "192.168.171.0",
           "type": "ether"
       },
...
192.168.171.130 | SUCCESS => {
   "ansible_facts": {
       "ansible_default_ipv4": {
           "address": "192.168.171.130",
...
[root@localhost ~]# ansible test -m setup -a 'filter=ansible_fqdn'   #获取主机名信息
192.168.171.130 | SUCCESS => {
   "ansible_facts": {
       "ansible_fqdn": "localhost.localdomain",
       "discovered_interpreter_python": "/usr/bin/python"
   },
   "changed": false
}
192.168.171.129 | SUCCESS => {
   "ansible_facts": {
       "ansible_fqdn": "localhost.localdomain",
       "discovered_interpreter_python": "/usr/bin/python"
   },
   "changed": false
}
[root@localhost ~]# ansible test -m setup -a 'filter=ansible_memory_mb'  #获取内存信息
192.168.171.129 | SUCCESS => {
   "ansible_facts": {
       "ansible_memory_mb": {
           "nocache": {
               "free": 254,
               "used": 718
           },
           "real": {
               "free": 120,
               "total": 972,
               "used": 852
           },
           "swap": {
               "cached": 0,
               "free": 2047,
               "total": 2047,
               "used": 0
           }
       },
...
192.168.171.130 | SUCCESS => {
   "ansible_facts": {
       "ansible_memory_mb": {
           "nocache": {
               "free": 245,
               "used": 727
           },
           "real": {
               "free": 111,
               "total": 972,
               "used": 861
           },
           "swap": {
               "cached": 0,
               "free": 2047,
               "total": 2047,
               "used": 0
           }
       },
...

常用的值,可用作变量使用
ansible_all_ipv4_addresses:仅显示ipv4的信息。
ansible_devices:仅显示磁盘设备信息。
ansible_distribution:显示是什么系统,例:centos,suse等。
ansible_distribution_major_version:显示是系统主版本。
ansible_distribution_version:仅显示系统版本。
ansible_machine:显示系统类型,例:32位,还是64位。
ansible_eth0:仅显示eth0的信息。
ansible_hostname:仅显示主机名。
ansible_fqdn:仅显示主机名。
ansible_kernel:仅显示内核版本。
ansible_lvm:显示lvm相关信息。
ansible_memtotal_mb:显示系统总内存。
ansible_memfree_mb:显示可用系统内存。
ansible_memory_mb:详细显示内存情况。
ansible_swaptotal_mb:显示总的swap内存。
ansible_swapfree_mb:显示swap内存的可用内存。
ansible_mounts:显示系统磁盘挂载情况。
ansible_processor:显示cpu个数(具体显示每个cpu的型号)。
ansible_processor_vcpus:显示cpu个数(只显示总的个数)。

3.ansible命令的常用模块使用-ad-hoc模式-批量操作实战的评论 (共 条)

分享到微博请遵守国家法律