playbooks是ansible管理配置、部署应用和编排的语言
可以使用playbooks来描述你想在远程主机执行的策略或一组步凑过程
ansible模块是工具,playbooks是方案
playbooks采用ymal语法结构
http://docs.ansible.com/ansible/YAMLSyntax.html
playbooks组成
Target section
定义将要执行playbooks的远程主机组
Variable section
定义playbooks运行时需要使用的变量
Task section
定义将要在远程主机上执行的任务列表
Handler section
定义task执行完成后需要调用的任务
例子:
---
- hosts:eddy
vars:
http_port:80
max_clients:200
remote_user:root
tasks:
- name:ensure apache is at the last version
yum:pkg=httpd state=latest
- name:write the apache config file
template:src=/srv/httpd.j2 dest=/etc/httd.conf
notify:
- restart apache
- name:ensure apache is running
service:name=httpd state=started
handlers:
- name:restart apache
service:name=httpd state=restarted
主机和用户
在playbooks中的每一个play都可以在那些机器、以什么身份完成,hosts一行可以是一个主机组或主机也是可以是多个的,中间以冒号分割,remote_user表示执行的用户
---
- hosts:eddy
---
- hosts:eddy:127.0.0.1
执行shell
---
- hosts: eddy:127.0.0.1
remote_user: root
tasks:
- name: check uptime
shell: /usr/bin/uptime
执行cp
---
- hosts: all
remote_user: root
tasks:
- name: check uptime
copy: src=/etc/hosts dest=/tmp/hosts owner=root group=root mode=0644
可以每一任务定义一个用户
---
- hosts: eddy:127.0.0.1
remote_user: root
tasks:
- name: check uptime
remote_user:ansible
sudo:yes
shell: /usr/bin/uptime
handlers 用于关注的资源发生变化时采取一定的操作
notify这个action可以用在每个play的最后被触发,这样可以避免多改变发生时每次都执行的操作
notify列出的操作称为handler
- name template configuration file
template: src=template.j2 dest=/etc/foo.conf
notify:
- restart memcached#引用handlers中定义的名称
- restart apache
handlers:
- name restart memcached
service:name=memcached state=restarted
- name restart apache
service:name=apache state=restarted
转载于:https://my.oschina.net/eddylinux/blog/533592