一.简介
ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。ansible是基于模块工作的,本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架。主要包括:
(1)、连接插件connection plugins:负责和被监控端实现通信;
(2)、host inventory:指定操作的主机,是一个配置文件里面定义监控的主机;
(3)、各种模块核心模块、command模块、自定义模块;
(4)、借助于插件完成记录日志邮件等功能;
(5)、playbook:剧本执行多个任务时,非必需可以让节点一次性运行多个任务。
运维工具分类:
agent: puppet,func.
agentless:ansible,fabric.ssh service.
ansible的特性:
基于python语言实现,由paramiko,pyYAM和jinjia2三个关键的模块。部署简单,使用agentless,默认使用ssh协议,(可以基于密钥认证或者inventory认证)主从模式:master:ansible。
二.Ansible安装配置
查看ansible安装包详情
[root@node1 /]# yum info ansible
1)安装ansible
[root@node1 ~]# yum install ansible -y
主配置文件:/etc/ansible/ansible.cfg
编辑主配置文件添加主机。
[root@node1 ansible]# cp hosts{,.bak}
[root@node1 ansible]# vim hosts
[web]
172.16.249.234
[db]
172.16.249.104
2)分别在三台主机上添加对方的密钥密钥文件。
[root@node1 ansible]# ssh-keygen -t rsa
[root@node1 ansible]# ssh-copy-id -i /root/.ssh/id_rsa.pub 172.16.249.104
配置好之后,同步三台主机的时间
[root@node1 ansible]# ssh root@172.16.249.104 ‘ntpdate 172.16.0.1’;ssh root@172.16.249.234 ‘ntpdate 172.16.0.1’;
查看模块文档:
[root@node1 ansible]# ansible-doc -l #列出所有模块
[root@node1 ansible]# ansible-doc -s yum #查看指定模块帮助
Usage: ansible <host-pattern> [options]
-f forks:启动的并发线程数
-m module_name:要使用的模块
-a args:模块特有的参数
[ansible的常见模块]
Command命令模块-默认模块
[root@node1 ansible]# ansible 172.16.249.104 -m command -a ‘date’ #查看时间
Corn模块-计划任务
state:presend安装,absent移除。
[root@node1 ansible]# ansible web -m cron -a ”minute=*/10′ job=”/bin/echo hello” name=test’ #加入state=absent参数即可移除命令
[root@node3 ~]# crontab -l
#Ansible: test
*/10 * * * * /bin/echo hello
User模块
[root@node1 /]# ansible all -m user -a ‘name=”test1″‘ #在所有主机上创建test1用户
Group模块
[root@node1 /]# ansible all -m group -a ‘name=mysql1 gid=306 system=yes’#创建组
[root@node1 /]# ansible all -m user -a ‘name=mysql1 uid=306 system=yes group=mysql1’ #把用户加入组
Copy模块
[root@node1 /]# ansible all -m copy -a ‘src=/etc/fstab dest=/tmp/fstab.an owner=root mode=640’# 复制本地文件到远程主机
[root@node1 /]# ansible all -m copy -a ‘content=”helo” dest=/tmp/test.an’ #content可以直接生成文件内容。取代src,两者不能同时使用。
File模块-设定文件属性
[root@node1 /]# ansible all -m file -a ‘owner=mysql1 group=mysql1 mode=644 path=/tmp/test.an’ #修改文件的权限。此处用的mysql1用户
Ping模块-测试主机的联通性
[root@node1 /]# ansible all -m ping #测试远程主机的联通性
Service模块 -控制服务的启动状态
[root@node1 /]# ansible all -a ‘service httpd status’ #查看服务的运行状态
[root@node1 /]# ansible all -m service -a ‘enabled=true name=httpd state=started’ #启动httpd
Shell模块-运行脚本
[root@node1 /]# ansible all -m shell -a ‘echo pwd | passwd –stdin test1’ #给指定用户添加密码
Script模块-将本地脚本复制至远程主机运行
[root@node1 /]# ansible all -m script -a ‘test.sh’ #此处脚本需要在当前目录
Yum模块-安装程序包
state=present,latest表示安装,absent表示卸载
[root@node1 /]# ansible all -m yum -a “name=zsh” #安装zsh程序包
[root@node1 /]# ansible all -m yum -a “name=zsh state=absent” #卸载程序包
Setup模块-收集远程主机的facts
[root@node1 /]# ansible all -m setup #查看每个节点向ansible报告的主机信息