(二)ansible 使用
阅读原文时间:2023年07月13日阅读:1

#ansible -m -a

#单个服务器
ansible 39.108.231.212 -m ping

#多个服务器,使用":"连接
ansible 192.168.1.190:192.168.1.191 -m ping

#test 组
ansible test -m ping

#所有服务器
ansible all -m ping

command、copy、fetch、file、ping、shell、service、setup、synchronize、yum

ansible-doc -l             #可以直接查看内置模块 ansible-doc -s file       #file为模块名

#重启主机 -f 线程数
ansible all –a "hostname" –f

#shell模块
ansible all -m shell -a "hostname"

#底层ssh 模块
ansible all -m raw -a "hostname"

#下发文件,且授权以及备份
ansible all –m copy –a "src=/etc/hosts dest=/tmp/hosts owner=root group=root backup=yes"

#备份的时候,只有在文件发生了变化的时候,那么会在远程主机上进行备份,而不是在本机上进行备份源文件,备份的是远程主机上被修改的文件

#上传文件(将把192.168.1.126服务器上的/root/test.sh文件上传到ansible 服务器,在/root目录下面保存为:192.168.1.126/root/test.sh)
ansible 192.168.1.126 -m fetch -a "src=/root/test.sh dest=/root"

#创建目录
ansible all -m file -a "path=/tmp/hidir state=directory owner=opadmin mode=777"

#创建空文件
ansible all -m file -a "path=/tmp/hifile state=touch owner=opadmin mode=777"

#创建软连接(/tmp/test2.txt 是目标服务器上的源文件)
ansible all -m file -a "path=/tmp/mytest.txt src=/tmp/test2.txt state=link"

#删除符号链接
ansible all -m file -a "path=/tmp/mytest.txt state=absent"

#为文件赋予权限
ansible all -m file -a "dest=a.txt mode=600 owner=opadmin group=opadmin"

#下载url 文件,保存至tmp目录下
ansible all -m get_url -a "url=http://download.redis.io/releases/redis-4.0.2.tar.gz dest=/tmp/"

#通过yum 模块安装git
ansible webserver -m yum -a "name=git state=latest"

#克隆仓库,保存至/tmp/fastdfs
ansible webserver -m git -a"repo=https://github.com/happyfish100/fastdfs.git dest=/tmp/fastdfs"

#每隔五分钟所有机器都去172..18.0.1上面同步一次时间
ansible all -m cron -a "name='timesync' job='/usr/sbin/ntpdate 172.18.0.1 &> /dev/null' minute='*/5'"
ansible all -m cron -a "name='check dirs' hour='5,2' job='ls -alh > /dev/null'"

#删除crontab
ansible all -m cron -a "name='timesync' job='/usr/sbin/ntpdate 172.18.0.1 &> /dev/null' minute='*/5' state=absent"

#注释crontab
ansible all -m cron -a "name='timesync' job='/usr/sbin/ntpdate 172.18.0.1 &> /dev/null' minute='*/5' state=present disabled=true"

#启动服务
ansible all -m service -a "name=nginx enabled=true state=started"

#重启服务
ansible all –m service –a "name=nginx state=restarted"

#停止服务
ansible all –m service –a "name=nginx state=stopped"

#安装
ansible all –m yum –a "name=httpd state=installed"

#安装指定版本的包
ansible all –m yum –a "name=httpd-2.6 state=installed"

#安装最新版本的包
ansible all –m yum –a "name=httpd state=latest"

#卸载安装包
ansible all –m yum –a "name=httpd state=removed"

# 增加用户
ansible all –m user –a "name=tom password=123456"

删除用户

ansible all –m user –a "name=tom state=absent"

ansible all –m setup

ansible all –m script –a "/root/demo/test.sh"

ansible all -m mount -a "name=/mnt/data src=/dev/sd0 fstype=ext4 opts=ro state=present"