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

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

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

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

1
2
3
4
5
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跳过)

 

 `如果复杂的命令怎么办?

  scrip允许在本地写脚本,拷贝到被管理端并执行脚本

  脚本不是shell脚本(如python\perl脚本等),可以没有-x

vim test.sh
#!/bin/bash
yum install -y httpd
systemctl start httpd

ansible test -m script -a "~/ansible/test.sh"
# test是主机的名称

 小结:

  command模块\shell模块的区别

    command不开始shell解释器,直接通过ssh执行命令,不支持bash的一些特有功能,如重定向等.

  script模块

    可以将提前编写好的脚本发送给远程主机,批量执行一组命令

 

`fiel模块可以创建文件\目录\链接;修怪权限与属性等

  幂等性:任意次执行所产生的影响均与一次执行的影响相同

ansible node1,node2 -m file -a "path=/tmp/file.txt state=touch"
# 新建文件
ansible node1,node2 -m file -a "path=/tmp/mydir state=directory"
# 创建目录
ansible node1,node2 -m file -a \
"path=/tmp/file.txt owner=sshd group=adm mode=0777"
# 修改文件或目录权限

 

 

 

 

 

 

  

 

posted @   真渡  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示