做了多年系统运维,觉得ansible是个不错的自动化运维工具,如果你是个系统运维工程师,手头上有很多台linux服务器需要管理维护,我觉得ansible对你来说是个不错的选择。ansible是基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。ansible是基于模块工作的,本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架。话不多说,下面简单介绍下linux环境下的安装配置和使用,已centos6.9为例。
- 使用yum安装
yum -y install ansible
2、ansible配置
# vim /etc/ansible/ansible.cfg
……
remote_port = 22
private_key_file = /path/to/file
……
基本都不需要更改,remote_port默认端口22,如果需要免密钥登陆更改private_key_file等。
3、主机组定义
# vim /etc/ansible/hosts
[myservergroup1]
192.168.0.1
192.168.0.2
[myservergroup2]
10.0.0.1
10.0.0.2
4、使用前先关闭selinux
setenforce 0
5、使用前先加载环境变量
. /usr/local/ansible/hacking/env-setup
6、使用实践
- 查看所有myservergroup1的服务器时间:
ansible myservergroup1 -m command -a "date" --ask-pass -u root
输入服务器密码,建议一组服务器密码相同,否则需要配置免密钥登陆。
- 所有服务器时间同步cn.pool.ntp.org
ansible all -m command -a "/usr/sbin/ntpdate cn.pool.ntp.org" --ask-pass -u root
- 执行服务器组内同一目录下脚本
ansible myservergroup2 -m shell -a "/tmp/test.sh"
- 统一加cron服务任务
ansible all -m cron -a "name='closenetwork' minute=01 hour=00 day=* month=* weekday=* job='/etc/init.d/network stop'" --ask-pass
统一删除cron服务任务
ansible all -m cron -a "name=closenetwork state=absent" --ask-pass
- 统一加linux账号
ansible all -m user -a "name=kelly group=kelly uid=555 comment='kelly' state=present"
- 统一更改密码(centos下)
ansible all -m shell -a "echo '123456789' |passwd --stdin root" --ask-pass -u root
本文介绍了 ansible 简单的设置过程,简单实用,让你轻松进入ansible 这个强大的自动化运维工具之门。