Ansible ad-hoc应用一
- 测试主机列表中的主机是否可以ping通
- 查看被管理主机的服务器信息(如时间、版本、内存等)
- 学习ansible-doc命令的用法
- 测试command与shell模块的区别
- 使用script模块在远程主机执行脚本(装软件包、启服务)
[root@control ansible]# ansible-doc -l #查看所有的模块
Ansible ad-hoc是一种通过命令行批量管理的方式,命令基本格式如下:
格式:ansible 主机集合 -m 模块名 -a "参数"
查看主机列表
[root@control ~]# cd ~/ansible
[root@control ansible]# ansible all --list-hosts # --list-hosts是ansible这个命令的固定选项,如同ls -a一样(-a是ls命令的固定选项)
hosts (5):
node1
node2
node3
node4
node5
测试远程主机是否能ping通
当需要远程多个主机或者多个组时,中间使用逗号分隔
- [root@control ansible]# ansible node1 -m ping #调用ping模块
- [root@control ansible]# ansible node1,webserver -m ping
- [root@control ansible]# ansible all -m ping #测试所有模块(绿色表示成功)
模块就是脚本(多数为Python脚本),多数脚本都支持参数,默认模块为command
- [root@control ansible]# ansible node1 -m command -a "uptime" #查看CPU负载
- [root@control ansible]# ansible node1 -m command -a "uname -r" #查看内核版本
- [root@control ansible]# ansible node1 -a "ip a s" #查看网卡信息
- [root@control ansible]# ansible all -a "date" #查看时间(所有机器的时间)
Shell模块
command和shell模块的区别,command不支持bash的特性。如管道和重定向等功能,但是shell模块可以支持,不可以使用shell模块执行交互命令,如vim、top等
- [root@control ansible]# ansible test -m command -a "ps | wc -l" #报错 #wc -l 统计
- [root@control ansible]# ansible test -m command -a "ls &" #报错
- [root@control ansible]# ansible test -m shell -a "ps aux | wc -l" #进程数量
- [root@control ansible]# ansible test -m shell -a "who" #登陆信息
- [root@control ansible]# ansible test -m shell -a "touch /tmp/txt.txt"
[WARNING]: Consider using the file module with state=touch rather than running 'touch'. If you
need to use command because file 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.node1 | CHANGED | rc=0 >>
#使用shell模块创建文件会有Warning警告提示,正常!!!
script模块
script模块会把-a后面的脚本拷贝到被管理端主机,然后执行这个脚本
- [root@control ansible]# vim ~/ansible/test.sh
- #!/bin/bash
- dnf -y install httpd
- systemctl start httpd
- [root@control ansible]# ansible test -m script -a "./test.sh" #test是主机组的名称,-m调用script模块,-a后面的./test.sh是上面创建脚本的相对路径和文件名,./是当前目录的意思,在当前目录下有个脚本叫test.sh
因为ansible远程的是node1,所以打开node1这台电脑,查看下是否安装了httpd软件、是否启动了服务
[root@node1 ~]# rpm -q httpd
httpd-2.4.37-21.module+el8.2.0+5008+cca404a3.x86_64
Ansible ad-hoc应用二
- 远程目标主机新建文件和目录、修改文件或目录的权限
- 在远程目标主机创建链接文件
- 删除远程目标主机上的文件或目录
- 将控制端本地的文件拷贝到被管理端
- 从被管理端下