六、Ansible自动化运维实战-ad-hoc命令行及模块应用

发布时间 2023-06-08 00:01:52作者: 真渡

`Ansible ad-hoc是一种通过命令行批量管理的方式

  格式: ansible 主机集合 -m 模块名 -a "参数"

  其它参数: -k使用密码远程 -i指定主机列表文件

cd ~/ansible
ansible all --list-hosts    #查看所有主机列表
ansible node1 -m ping    #调用ping模块
ansible node1,node2 -m ping
ansible webserver -m ping

 

`模块就是脚本(多数为Python脚本)

  多数脚本都支持参数

  默认模块为command

ansible node1 -m command -a "uptime"
ansible node1 -m command -a "uname -r"
ansible node1 -m command -a "ip a s"
ansible node1 -a "ip a s"
ansible all -a "date"

 

`如何获得帮助

  ansible总共有哪些模块

  每个模块支持那些选择

ansible-doc -l    #列出所有模块
ansible-doc -l | grep yum    #过滤模块
ansible-doc yum    #查看模块帮助

 

`commend和shell模块的区别

  command模块的命令不启动shell,直接通过ssh执行命令

  command不支持bash的特性,如管道重定向等功能

  所有需要调用shell的功能都无法使用

ansible test -m command -a "ps | wc -l"    #报错
ansible test -m command -a "ls &"    #报错

 

`shell模块会启动shell执行命令

  不可以使用shell模块执行交互命令,如vim\top等

  shell

ansible test -m shell -a "ps aux | wc -l"    #查看进程数量
ansible test -m shell -a "who"    #登陆信息
ansible test -m shell -a "touch /tmp/txt.txt"

 

`ansible使用SSH远程连接被管理主机

  退出SSH后所有状态失效

  chdir

ansible test -m shell -a "cd /tmp"    
#切换目录
ansible test -m shell -a "touch my.txt"
#创建文件 (注意:没有指定路径,是在家目录创建的文件)
ansible test -m shell -a "ls /tmp/my.txt"
#查看文件失败
--------------
ansible test -m shell -a "chdir=/tmp touch my.txt"
#使用chdir参数切换工作目录

 

`shell模块支持判断

  creates 文件名: 文件名存在,则不执行shell命令

  removes 文件名:文件名不存在,则不执行shell命令

ansible test -m shell -a "ssh-keygen -f ~/.ssh/id_rsa -N '' creates=~/.ssh/id_rsa"
# 如果已经有密钥文件id_rsa,则不创建密钥(skip跳过)

ansible test -m shell -a "unzip xx.zip removes=/bin/unzip"
# 如果没有安装unzip软件包,则不执行解压命令(skip跳过)