在这个风起云涌的自动化运维时代,选择一个拿手的自动化工具不仅可以解放双手,更重要的是工作效率大大提升!
Ansible特点 就目前的优势来说:
①轻量级;②不需要安装客户端,通过sshd通信;③基于模块工作,配置更加简单,容易上手。④使用Python开发,模块多⑤ 安装十分简单,centos上可直接yum安装(ansible已经被redhat公司收购,它在github上是一个非常受欢迎的开源软件,github地址https://github.com/ansible/ansible)
准备两台机器,前面我们做实验的三台机器zhdy01,zhdy02,zhdy03
yum install -y ansible
zhdy01上生成密钥对
ssh-keygen -t rsa
把公钥放到zhdy02和zhdy03上,设置密钥认证
vi /etc/ansible/hosts //增加
[testhost]
192.168.59.138
192.168.59.139
说明: testhost为主机组名字,自定义的。 下面两个ip为组内的机器ip(要是想只写主机名,必须要在/etc/hosts下面增加IP+主机名)
如上在真实的运维工作中,其实是分为很多个组的,有devgroup,testgroup,webgroup,dbgroup等。
ansible testhost -m command -a 'w'
这样就可以批量执行命令了。这里的testhost 为主机组名,-m后边是模块名字,-a后面是命令。
当然我们也可以直接写一个ip
ansible 192.168.59.138 -m command -a 'hostname'
错误:"msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"
解决:yum install -y libselinux-python
还有一个模块就是shell同样也可以实现
ansible testhost -m shell -a 'w'
Ansible功能之一shell(远程执行脚本模块)也是我蛮喜欢的直接支持 管道符 (但是 -m command 是不可以的!)
ansible 192.168.59.138 -m shell -a "cat /etc/passwd| grep root"
ansible testhost -m copy -a "src=/tmp/tt dest=/tmp/tt/ owner=root group=root mode=0755"
注意:源目录会放到目标目录下面去,如果目标指定的目录不存在,它会自动创建。 如果拷贝的是文件,dest指定的名字和源如果不同,并且它不是已经存在的目录,相当于拷贝过去后又重命名。但相反,如果dest是目标机器上已经存在的目录,则会直接把文件拷贝到该目录下面。
ansible testhost -m copy -a "src=/etc/passwd dest=/tmp/pa.txt"
这里的/tmp/pa.txt和源机器上的/etc/passwd是一致的,如果目标主机已经有了pa.txt文件这样操作会直接覆盖。不存在则直接创建。
在开始前,必须要说的一句话是,脚本一定要赋予 755权限! 755权限!! 755权限!!! 强调三遍的意思是我吃过亏:)
脚本路径+脚本名+脚本内容:
/usr/local/sbin/time.sh
#!/bin/bash
echo `date` > /tmp/ansible_test.txt
ansible testhost -m copy -a "src=/usr/local/sbin/time.sh dest=/usr/local/sbin/time.sh mode=0755"
ansible testhost -m shell -a "/usr/local/sbin/time.sh"
[[email protected] ~]# cat /tmp/ansible_test.txt
2017年 11月 07日 星期二 17:21:50 CST
创建一个新的cron计划:
ansible testhost -m cron -a "name='test cron' job='/usr/local/sbin/time.sh' weekday=6"
//检查客户端情况:
[[email protected] ~]# crontab -l
# Lines below here are managed by Salt, do not edit
#Ansible: test cron
* * * * 6 /usr/local/sbin/time.sh
再次更改不同的时间:
ansible testhost -m cron -a "name='test cron' job='/usr/local/sbin/time.sh' minute=08 hour=08 day=08 month=08 weekday=08"
[[email protected] ~]# crontab -l
# Lines below here are managed by Salt, do not edit
#Ansible: test cron
08 08 08 08 08 /usr/local/sbin/time.sh
//时间表示:分钟 minute 小时 hour 日期 day 月份 month
一旦任务计划制定,千万不要手动去修改,这样下次再次远程更新会报错!~
删除任务计划:
ansible testhost -m cron -a "name='test cron' state=absent"