Ansible 是一个开源的基于 OpenSSH 的自动化配置管理工具。可以用它来配置系统、部署软件和编排更高级的 IT 任务,比如持续部署或零停机更新。管理员可以通过 Ansible 在成百上千台计算机上同时执行指令(任务),这是官方文档。
配置组
Ansible 可同时操作属于一个组的多台主机,在 /etc/ansible/hosts 中配置组
| $ vim /etc/ansible/hosts
 
 [spark]
 dell-r730-[1:4]
 
 [hdfs]
 dell-r730-[1:4]
 dell-r730-7
 
 | 
使用时可分为 ad-hoc 和 playbook
ad-hoc
在命令行敲入的shell命令,去执行些简单的任务:
ansible 组名 -m 模块名 -a 具体操作 [-u 用户名] [--sudo] [-f 10]
- -m模块名
- -a具体操作,一般是k v结构。
- -u默认以当前用户的身份执行命令,也可手动指定
- --sudo通过 sudo 去执行命令( passwordless 模式 )
- -f并发量
下面介绍些常用模块
commond 和 shell
commond 是默认的模块
commond 和 shell 都是直接敲命令的。command 更安全,但不支持 shell 变量,也不支持管道等 shell 相关的东西
shell使用变量时也存在限制,所以尽量不要敲太复杂的命令。
| $ ansible zxy -a "date"
 
 
 $ ansible zxy -m shell -a "cat /etc/hosts > test.txt"
 
 | 
file 和 copy
file 用于创建(删除)文件或文件夹,也可更改所有者权限
copy 用与复制文件
(我觉得有点麻烦,没有commnd来的快点)
| $ ansible zxy -m file -a "path=/home/cluster/testfile state=touch"
 
 
 $ ansible zxy -m file -a "path=/home/cluster/testdir state=directory"
 
 
 $ ansible zxy -m file -a "path=/home/cluster/testdir state=absent"
 
 
 $ ansible zxy -m file -a "path=/home/cluster/testdir state=directory owner=cluster mode=0777 recurse=true"
 
 
 
 $ ansible zxy -m copy -a "src=/home/cluster/testfile dest=/home/cluster/testfile2 owner=cluster mode=0777"
 
 | 
synchronize
文件或文件夹同步,有 push(默认)和 pull 模式。
默认启用了archive参数,该参数默认开启了recursive, links, perms, times, owner,group和-D参数。
可加 --exclude=xxx 忽略指定文件
| $ ansible zxy -m synchronize -a "src=/home/cluster/testfile dest=/home/cluster/testfile"
 | 
ping
playbook
将一系列有序任务保存成yml文件,方便多次使用和有序的执行指定的任务。
ansible-playbook playbook.yml
| ---- hosts: 组名
 vars:
 变量名: 值
 remote_user: root
 tasks:
 - name: 描述任务(自定义)
 模块名: 具体操作
 - name: xxxx
 模块名: xxxxx
 notify:
 - 钩子名( task 结束且该 task 有意义(改变了东西)时被触发,只执行一次)
 handlers:
 - name: 钩子名
 模块名: 具体操作
 
 | 
| ---- hosts: webservers
 vars:
 http_port: 80
 max_clients: 200
 remote_user: root
 tasks:
 - name: ensure apache is at the latest version
 yum: pkg=httpd state=latest
 - name: write the apache config file
 template: src=/srv/httpd.j2 dest=/etc/httpd.conf
 notify:
 - restart apache
 - name: ensure apache is running
 service: name=httpd state=started
 handlers:
 - name: restart apache
 service: name=httpd state=restarted
 
 |