1、安装ansible
rpm -ivh https://mirrors.aliyun.com/epel/6Server/x86_64/Packages/e/epel-release-6-8.noarch.rpm
yum -y install ansible
ssh-keygen -t rsa -P ''
ssh-copy-id -i /root/.ssh/id_rsa.pub root@
ssh-copy-id -i /root/.ssh/id_rsa.pub root@
ssh-copy-id -i /root/.ssh/id_rsa.pub root@
ssh-copy-id -i /root/.ssh/id_rsa.pub root@
2、ansible主机配置
grep -v ^# /etc/ansible/hosts |grep -v ^$
[web]
[mysql]
3、ansible简单应用
查看命令帮助
ansible-doc -s group
检测主机是否在线
ansible all -m ping
在远程主机执行命令并返回结果[-m command]可省
ansible all [-m command]-a 'date'
复制文件
ansible mysql -m copy -a "src=/etc/sysconfig/network-scripts/ifcfg-eth0 dest=/tmp"
crontab计划任务
ansible all -m cron -a 'name="custom job" minute=*/3 hour=* day=* month=* weekday=* job="usr/sbin/ntpdate "'
创建用户组和用户
ansible all -m group -a "gid=306 system=yes name=mysql"
ansible all -m user -a "group=mysql name=mysql uid=306 shell=/sbin/nologin"
删除用户和用户组
ansible all -m user -a "state=absent name=mysql"
ansible all -m group -a "state=absent name=mysql"
yum安装软件
ansible all -m yum -a "state=present name=httpd"
启动服务
ansible all -m service -a "state=started name=httpd enabled=yes"
停止服务
ansible all -m service -a "state=stopped name=httpd enabled=no"
yum卸载软件
ansible web -m yum -a "state=removed name=httpd"
4、ansible高级应用ansible-playbook
安装httpd,通过控制机复制配置文件到被控制机,并重启被控制器上的httpd服务
cat httpd.yaml
- hosts : all
remote_user : root
tasks :
- name : ensure apache latest version
yum : state=latest name=httpd
- name : apache configure file
copy : src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf force=yes
notify :
- restart httpd
handlers :
- name : restart httpd
service : name=httpd state=restarted
ansible-playbook httpd.yaml
ansible all -a 'rpm -q httpd'