Ansible 之Playbook

       ansbile playbook是一系列ansible命令的集合,利用yaml 语言编写,playbook命令根据自上而下的顺序依次执行。同时,playbook开创了不少特性,它能够容许你传输某个命令的状态到后面的指令,如你能够从一台机器的文件中抓取内容并附为变量,而后在另外一台机器中使用,这使得你能够实现一些复杂的部署机制,这是ansible命令没法实现的.nginx

Playbook是Ansible的配置,部署,编排语言。他们能够被描述为一个须要但愿远程主机执行命令的方案,或者一组IT程序运行的命令集合。shell

playbook的构成apache

      playbook是由一个或多个"play"组成的列表。play的主要功能在于将事先归并为一组的主机装扮成事先经过ansible中的task定义好的角色。从根本上来说所谓task无非是调用ansible的一个module。将多个play组织在一个playbook中便可以让它们联同起来按事先编排的机制同唱一台大戏。其主要有如下四部分构成:vim

Playbooks
  Variables      #变量元素,可传递给Tasks/Templates使用;
  Tasks          #任务元素,即调用模块完成任务;
  Templates      #模板元素,可根据变量动态生成配置文件;
  Hadlers        #处理器元素,一般指在某事件知足时触发的操做;
  Roles          #角色元素

      使用Playbook时经过ansible-playbook命令使用,它的参数和ansible命令相似,如参数-k(–ask-pass) 和-K (–ask-sudo) 来询问ssh密码和sudo密码,-u指定用户,这些指令也能够经过规定的单元写在playbook里。centos

ansible-playbook的简单使用方法:ssh

ansible-playbook /etc/ansible/site.yml

如下是简单的playbook例子(play能够有多个):spa

1.使用playbook 实现新增一个用户的功能:rest

#vim create_user.yml code

---
- hosts: test gather_facts: false user: root vars: user: "user1" tasks: - name: create user user: name="{{ user }}" createhome=yes

各行参数详解:对象

hosts参数指定了对哪些主机进行参做,test为定义的主机组.
user参数指定了使用什么用户登陆远程主机操做;
gather_facts参数指定了在如下任务部分执行前,是否先执行setup模块获取主机相关信息.
vars参数,指定了变量,这里指定一个user变量,其值为user1,须要注意的是,变量值必定要用引号引住;
task指定了一个任务,其下面的name参数是对任务的描述,在执行过程当中会打印出来
user提定了调用user模块,name是user模块里的一个参数,而增长的用户名字调用了上面user变量的值,createhome=yes表示建立用户家目录,也是user模块的参数对象.

一样,若是想实现把这个新增的用户删除,只需将该playbook文件的最后一行替换为以下行再执行相应的playbook便可:
user: name="{{ user }}" state=absent remove=yes

2.使用playbook更改一组主机主机名的方法:

---
- hosts : test remote_user : root tasks : - name : show hostname shell : hostname - name: show ipaddress command : ip addr - hostname : name=benet.develop.com

说明:在tasks任务中,调用了shell和command模块来执行查询命令,- hostname是使用hostname模块的name方法来更改主机名.

3.使用playbook安装apache服务实例:

---
- hosts: test remote_user: root tasks: - name: Install the latest version of apache. yum: name=httpd state=latest - name: write the apache config file copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/httpd.conf notify: - restart httpd service - name: Start the apache service service: name=httpd state=started handlers: - name: restart httpd service service: name=httpd state=restarted #注意:在notify中定义内容必定要和tasks中定义的 - name 内容同样,这样才能达到触发的效果,不然会不生效。

4.使用playbook安装Nginx实例:

---
- hosts: test tasks: - name: Install nginx Depend on the package yum: pkg={{ item }} state=latest with_items: - openssl-devel - gcc - pcre-devel - zlib-devel - name: Installing NGINX repo rpm yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm

  - name: Installing NGINX yum: name=nginx state=latest - name: write the NGINX config file copy: src=/tmp/nginx.conf dest=/etc/nginx/nginx.conf notify: - restart NGINX service - name: Start the NGINX service service: name=nginx state=started handlers: - name: restart NGINX service service: name=nginx state=restarted
相关文章
相关标签/搜索