ansible之playbook

ansible之playbook


1. 什么是YAML

YAML(/ˈjæməl/,尾音类似camel骆驼)是一个可读性高,用来表达数据序列的格式。YAML参考了其他多种语言,包括:C语言、Python、Perl,并从XML、电子邮件的数据格式(RFC 2822)中获得灵感。Clark Evans在2001年首次发表了这种语言,另外Ingy döt Net与Oren Ben-Kiki也是这语言的共同设计者。目前已经有数种编程语言或脚本语言支持(或者说解析)这种语言。

YAML是"YAML Ain't a Markup Language"(YAML不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言),但为了强调这种语言以数据做为中心,而不是以标记语言为重点,而用反向缩略语重命名。

YAML的语法和其他高级语言类似,并且可以简单表达清单、散列表,标量等数据形态。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件、倾印除错内容、文件大纲(例如:许多电子邮件标题格式和YAML非常接近)。

2. Playbook的核心元素

  • Hosts:指明playbook应用的对象
  • Tasks:任务列表(核心)
  • Variables:一个值会被引用多次,且引用的过程中有可能会发生变化,可用变量来代替。可有效简化配置过程。
  • Templates:包含了模板语法的文本文件;
  • Handlers:由特定条件满足时才会触发的任务;

3. playbook的基础组件:

  • Hosts:运行指定任务的主机列表
  • remoute_user/sudo_user: 在远程主机上执行任务的用户
    • sudo_user必须为可执行需要任务的用户
  • tasks:任务列表
    • 模块,模块参数
    • 格式:
      1. action: module arguments
      2. module: arguments
        注意:shell和command模块后面直接跟命令,而非key=value类的参数列表
      3. 某任务的状态在运行后为changed时,可通过“notify”通知给相应的handlers
      4. 任务可以通过"tags“打标签,而后可在ansible-playbook命令上使用-t指定进行调用
  • 运行playbook的方式
    1. 测试
      • ansible-playbook --check 只检测可能会发生的改变,但不真正执行操作
      • ansible-playbook --list-hosts 列出运行任务的主机
      • ansible-playbook --list-tasks 列出要运行的任务列表
      • ansible-playbook --syntax-check 语法检查
      • ansible-playbook --list-tags 列出所有可用的标签
      • ansible-playbook -t TAGS , --tags=TAGS 只运行指定标签的任务
      • ansible-playbook --skip-tigs=SKIP_TIGS 跳过指定标签的任务
      • ansible-playbook --list-tasks 列出所有任务列表
    2. 运行
      • ansible-playbook YAML_FILE

一个简单的示例: 远程主机np1.lxk.com安装memcached并设置开机自动启动

  1. 编辑文件memcached.yaml,添加以下内容:
- hosts: np1.lxk.com
  remote_user: root
  tasks:
        - name: 'install memcached package'
          yum: 'name=memcached state=installed'
        - name: 'start memcached server'
          service: 'name=memcached enabled=true state=started'
- hosts: np2.lxk.com
  remote_user: root
  tasks:
        - name: install memcached package
          yum: name=memcached state=installed
        - name: start memcached server
          service: name=memcached enabled=true state=started
  1. 测试语法:
[root@nfs ansible_workshop]# ansible-playbook --syntax-check memcached.yaml 

playbook: memcached.yaml
  1. 测试运行:

PLAY [np1.lxk.com] ****

TASK [Gathering Facts] ****
ok: [np1.lxk.com]

TASK [install memcached package] **
ok: [np1.lxk.com]

TASK [start memcached server] *****
ok: [np1.lxk.com]

PLAY [np2.lxk.com] ****

TASK [Gathering Facts] ****
ok: [np2.lxk.com]

TASK [install memcached package] **
changed: [np2.lxk.com]

TASK [start memcached server] *****
changed: [np2.lxk.com]

PLAY RECAP ****
np1.lxk.com : ok=3 changed=0 unreachable=0 failed=0
np2.lxk.com : ok=3 changed=2 unreachable=0 failed=0


4. 运行memcached.yaml

```leaf
[root@nfs ansible_workshop]# ansible-playbook memcached.yaml 

PLAY [np1.lxk.com] ********************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np1.lxk.com]

TASK [install memcached package] ******************************************************************************************
ok: [np1.lxk.com]

TASK [start memcached server] *********************************************************************************************
ok: [np1.lxk.com]

PLAY [np2.lxk.com] ********************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np2.lxk.com]

TASK [install memcached package] ******************************************************************************************
changed: [np2.lxk.com]

TASK [start memcached server] *********************************************************************************************
changed: [np2.lxk.com]

PLAY RECAP ****************************************************************************************************************
np1.lxk.com                : ok=3    changed=0    unreachable=0    failed=0   
np2.lxk.com                : ok=3    changed=2    unreachable=0    failed=0   
  1. 在目标主机上查看:
[root@np1 ~]# systemctl is-enabled memcached
enabled                     #已设置为开机自动运行
[root@np1 ~]# systemctl status memcached            #已经启动成功
● memcached.service - Memcached
   Loaded: loaded (/usr/lib/systemd/system/memcached.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2018-06-10 12:20:56 CST; 5min ago
 Main PID: 18030 (memcached)
   CGroup: /system.slice/memcached.service
           └─18030 /usr/bin/memcached -u memcached -p 11211 -m 64 -c 1024

Jun 10 12:20:56 np1.lxk.com systemd[1]: Started Memcached.
Jun 10 12:20:56 np1.lxk.com systemd[1]: Starting Memcached...
  1. 补充:查看要执行任务的主机:
[root@nfs ansible_workshop]# ansible-playbook --check --list-hosts memcached.yaml 

playbook: memcached.yaml

  play #1 (np1.lxk.com): np1.lxk.com    TAGS: []
    pattern: [u'np1.lxk.com']
    hosts (1):
      np1.lxk.com

  play #2 (np2.lxk.com): np2.lxk.com    TAGS: []
    pattern: [u'np2.lxk.com']
    hosts (1):
      np2.lxk.com
  • handlers:
    • 任务,在特定条件下触发
    • 接收到其它任务的通知时被触发
      • notify: HANDLER TASK NAME

示例: 为memcached提供监听在11311端口的配置文件,并重启服务

  1. 修改yuml文件 memcached_v1.yuml
- hosts: np1.lxk.com
  remote_user: root
  tasks:
        - name: 'install memcached package'
          yum: 'name=memcached state=installed'
        - name: 'install conf file'
          copy: 'src=/etc/sysconfig/memcached dest=/etc/sysconfig/memcached'
          notify: 'restart memcached service'
        - name: 'start memcached server'
          service: 'name=memcached enabled=true state=started'
  handlers:
        - name: 'restart memcached service'
          service: 'name=memcached state=restarted'
  1. 语法检测:
[root@nfs ansible_workshop]# ansible-playbook --syntax-check memcached_v2.yaml

playbook: memcached_v2.yaml
  1. check yuml文件是否可运行
跟下面一步内容相同,只是语句不同,语句如下:
~]# ansible-playbook --check memcached_v2.yaml
  1. 运行:
[root@nfs ansible_workshop]# ansible-playbook memcached_v2.yaml 

PLAY [np1.lxk.com] ********************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np1.lxk.com]

TASK [install memcached package] ******************************************************************************************
ok: [np1.lxk.com]

TASK [install conf file] **************************************************************************************************
changed: [np1.lxk.com]

TASK [start memcached server] *********************************************************************************************
ok: [np1.lxk.com]

RUNNING HANDLER [restart memcached service] *******************************************************************************
changed: [np1.lxk.com]

PLAY RECAP ****************************************************************************************************************
np1.lxk.com                : ok=5    changed=2    unreachable=0    failed=0   
  1. 查看np1.lxk.com上memcached监听的端口:
[root@np1 ~]# systemctl status memcached
● memcached.service - Memcached
   Loaded: loaded (/usr/lib/systemd/system/memcached.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2018-06-10 13:28:42 CST; 5min ago
 Main PID: 19732 (memcached)
   CGroup: /system.slice/memcached.service
           └─19732 /usr/bin/memcached -u memcached -p 11311 -m 64 -c 1024

Jun 10 13:28:42 np1.lxk.com systemd[1]: Started Memcached.
Jun 10 13:28:42 np1.lxk.com systemd[1]: Starting Memcached...

#通过ss -tnlp也可以查看,但是太长了。这里也可以看到memcached监听的端口为11311

注:若配置文件发生改变,再一次运行memcached_v2.yaml时,会触发复制配置文件并重启服务。配置文件不发生改变,不会触发。

  • variables:
    1. facts:内建变量,可直接调用
      注意:可使用setup模块直接获取目标主机的facters
    2. 用户自定义变量
      • 通过ansible-playbook命令的选项调用函数
        -e VARS, --extra-vars=VARS
      • 在playbook中定义变量的方法
        vars:
        '- var1: value1'
        '- var2: value2'
    3. 变量引用:{{ variable }}

示例:通过自定义变量安装tree

  1. 编辑yaml文件pkgs.yaml
- hosts: np1.lxk.com
  remote_user: root
  vars:
  - pkgname: 'tree'
  tasks:
  - name: install {{ pkgname }}
    yum: name={{ pkgname }} state=installed
  1. 安装
[root@nfs ansible_workshop]# ansible-playbook pkgs.yaml 

PLAY [np1.lxk.com] ********************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np1.lxk.com]

TASK [install tree] *******************************************************************************************************
ok: [np1.lxk.com]

PLAY RECAP ****************************************************************************************************************
np1.lxk.com                : ok=2    changed=0    unreachable=0    failed=0   

示例2:使用pkgs.yaml文件,不修改文件内容,通过ansible-playbook中的-e选项给定变量的参数

[root@nfs ansible_workshop]# ansible-playbook --check -e pkgname='httpd' pkgs.yaml 

PLAY [np1.lxk.com] ********************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np1.lxk.com]

TASK [install httpd] ******************************************************************************************************
ok: [np1.lxk.com]

PLAY RECAP ****************************************************************************************************************
np1.lxk.com                : ok=2    changed=0    unreachable=0    failed=0   

可以看到运行时的TASK对象变为了httpd

  1. 通过roles传递变量
  2. Host Inventory
    • 用户自定义变量
      1. 向不同的主机传递不同的变量
        IP/HOSTNAME varaiable=value var2=value2
      2. 向组中的主机传递相同的变量
        [groupname:vars]
        variable=value
    • invertory参数
      • 用于定义ansible远程连接目标主机时使用的参数,而非传递给playbook的变量
        ansible_ssh_host
        ansible_ssh_port
        ansible_ssh_user
        ansible_ssh_pass
        ansbile_sudo_pass

示例:组中的主机传递参数:
/etc/ansible/hosts配置:

[root@nfs ansible_workshop]# tail -15 /etc/ansible/hosts
[db]
node1.lxk.com
node2.lxk.com
[db:vars]
pkgname='mariadb-server'

[web]
np1.lxk.com
np2.lxk.com

[web:vars]
pkgname='nginx'

[nfs]
nfs.lxk.com

yaml文件内容:

- hosts: db
  remote_user: root
  tasks:
  - name: install {{ pkgname }}
    yum: name={{ pkgname }} state=installed

- hosts: web
  remote_user: root
  tasks:
  - name: install {{ pkgname }}
    yum: name={{ pkgname }} state=installed

干跑模式结果:

[root@nfs ansible_workshop]# ansible-playbook --check pkgs.yaml 

PLAY [db] *****************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [node2.lxk.com]
ok: [node1.lxk.com]

TASK [install mariadb-server] *********************************************************************************************
ok: [node2.lxk.com]
ok: [node1.lxk.com]

PLAY [web] ****************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np2.lxk.com]
ok: [np1.lxk.com]

TASK [install nginx] ******************************************************************************************************
changed: [np2.lxk.com]
changed: [np1.lxk.com]

PLAY RECAP ****************************************************************************************************************
node1.lxk.com              : ok=2    changed=0    unreachable=0    failed=0   
node2.lxk.com              : ok=2    changed=0    unreachable=0    failed=0   
np1.lxk.com                : ok=2    changed=1    unreachable=0    failed=0   
np2.lxk.com                : ok=2    changed=1    unreachable=0    failed=0   

通过以上示例可以看出,在hosts文件中也可以传递参数。

示例:通过invertory参数连接目标主机

  1. 修改要连接的主机监听的端口为22022
[root@node1 ~]# vim /etc/ssh/sshd_config 
增加以下内容:
port 22
port 22022
[root@node1 ~]# systemctl restart sshd
[root@node1 ~]# ss -tnl
State       Recv-Q Send-Q                Local Address:Port                               Peer Address:Port              
LISTEN      0      128                               *:22                                            *:*                  
LISTEN      0      100                       127.0.0.1:25                                            *:*                  
LISTEN      0      128                               *:22022                                         *:*                  
LISTEN      0      50                                *:3306                                          *:*                  
LISTEN      0      128                              :::22                                           :::*                  
LISTEN      0      100                             ::1:25                                           :::*                  
LISTEN      0      128                              :::22022                                        :::*      
  1. 编辑/etc/ansible/hosts文件连接目标服务器
node1.lxk.com ansible_ssh_port=22022
node2.lxk.com ansible_ssh_root=root ansible_ssh_pass=magedu.com
  1. 编辑yaml文件内容如下:
[root@nfs ansible_workshop]# cat pkgs.yaml 
- hosts: all
  remote_user: root
  vars:
  - pkgname: 'tree'
  tasks:
  - name: install {{ pkgname }}
    yum: name={{ pkgname }} state=installed
  1. 向目标主机传递命令,连接成功。
[root@nfs ansible_workshop]# ansible all -m shell -a '[[ -f /etc/hosts ]]'
node1.lxk.com | SUCCESS | rc=0 >>

node2.lxk.com | SUCCESS | rc=0 >>
  • 模板:templates
    文本文件,嵌套有脚本(使用模板编程语言编写)
    Jinja2:
        字面量:
            字符串:使用单引号或双引号;
            数字:整数,浮点数;
            列表:[item1, item2, ...]
            元组:(item1, item2, ...)
            字典:{key1:value1, key2:value2, ...}
            布尔型:true/false
    运算符:                                
        算术运算:
            +, -, *, /, //, %, **

        比较操作:
            ==, !=, >, >=, <, <=

        逻辑运算:
            and, or, not 

示例:

- hosts: websrvs
  remote_user: root
  tasks:
    - name: install nginx
    yum: name=nginx state=present
    - name: install conf file
    template: src=files/nginx.conf.j2 dest=/etc/nginx/nginx.conf
    notify: restart nginx
    tags: instconf
    - name: start nginx service
    service: name=nginx state=started
    handlers:
    - name: restart nginx
    service: name=nginx state=restarted                 

模板配置文件 :nginx.conf.j2

worker_processes {{ ansible_processor_vcpus - 1 }};
listen {{ http_port }};
server_name 

示例1: 复制模板至目标主机:
主机列表:

node1.lxk.com
node2.lxk.com
np1.lxk.com
np2.lxk.com
nfs.lxk.com
  1. 编辑模板文件:
[root@nfs ansible_workshop]# cat test.j2 
hostname: {{ansible_fqdn }}         #调用系统变量中的主机名
vars: {{ pkgname }}                 #调用自定义变量,可在ansible-playbook中用-e选项给定
  1. 编辑yaml文件,复制test.j2文件至目标主机
[root@nfs ansible_workshop]# cat test.yaml 
- hosts: all
  remote_user: root
  tasks:
  - name: install file
    template: src=/root/ansible_workshop/test.j2 dest=/tmp/test.conf
  1. 执行复制,命令行中给定参数pkgname的值为somepkg:
[root@nfs ansible_workshop]# ansible-playbook -e pkgname='somepkg' test.yaml 

PLAY [all] ****************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [node2.lxk.com]
ok: [np1.lxk.com]
ok: [np2.lxk.com]
ok: [node1.lxk.com]
ok: [nfs.lxk.com]

TASK [install file] *******************************************************************************************************
changed: [np2.lxk.com]
changed: [np1.lxk.com]
changed: [node2.lxk.com]
changed: [node1.lxk.com]
changed: [nfs.lxk.com]

PLAY RECAP ****************************************************************************************************************
nfs.lxk.com                : ok=2    changed=1    unreachable=0    failed=0   
node1.lxk.com              : ok=2    changed=1    unreachable=0    failed=0   
node2.lxk.com              : ok=2    changed=1    unreachable=0    failed=0   
np1.lxk.com                : ok=2    changed=1    unreachable=0    failed=0   
np2.lxk.com                : ok=2    changed=1    unreachable=0    failed=0   

示例2: 在目标主机上安装tomcat,配置文件中jvmRoute设置为各自主机名,并提供manaager-gui和admin-gui的登录用户

  1. 修改tomcat默认配置文件,在engine处添加jvmRoute={{ ansible_hostname }}
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="{{ ansible_hostname }}" >
  1. 编辑tomcat-user.xml文件,添加以下内容:
<role rolename="manaager-gui"/>
<role rolename="admin-gui"/>
<user username="tomcat" password="tomcat" roles="manager-gui,admin-gui"/>
  1. 编辑yaml文件:server-user.xml是通用配置,不用做成j2文件,server.xml内有变量,需要用template模块
 - hosts: tomcat
   remote_user: root
   tasks:
   - name: install tomcat-admin-webapps
     yum: name=tomcat-admin-webapps state=installed
   - name: install tomcat-users.xml
     copy: src=/root/ansible_workshop/tomcat-users.xml dest=/etc/tomcat/tomcat-users.xml owner=root group=tomcat mode=0640
     notify: restart tomcat
   - name: install server.xml
     template: src=/root/ansible_workshop/server.xml.j2 dest=/etc/tomcat/server.xml owner=root group=tomcat
   - name: start tomcat
     service: name=tomcat state=started
   handlers:
   - name: restart tomcat
     service: name=tomcat state=restarted
  1. 执行操作:
[root@nfs ansible_workshop]# ansible-playbook tomcat.yaml 

PLAY [tomcat] *************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np2.lxk.com]
ok: [np1.lxk.com]

TASK [install tomcat-admin-webapps] ***************************************************************************************
ok: [np2.lxk.com]
ok: [np1.lxk.com]

TASK [install tomcat-users.xml] *******************************************************************************************
changed: [np2.lxk.com]
changed: [np1.lxk.com]

TASK [install server.xml] *************************************************************************************************
changed: [np1.lxk.com]
changed: [np2.lxk.com]

TASK [start tomcat] *******************************************************************************************************
changed: [np2.lxk.com]
changed: [np1.lxk.com]

RUNNING HANDLER [restart tomcat] ******************************************************************************************
changed: [np2.lxk.com]
changed: [np1.lxk.com]

PLAY RECAP ****************************************************************************************************************
np1.lxk.com                : ok=6    changed=4    unreachable=0    failed=0   
np2.lxk.com                : ok=6    changed=4    unreachable=0    failed=0   
  1. 查看目标主机上配置文件:
    np1:
[root@np1 ~]# grep np1 /etc/tomcat/server.xml
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="np1" >
[root@np1 ~]# cat /etc/tomcat/tomcat-users.xml | head -44 | tail -3
<role rolename="manaager-gui"/>
<role rolename="admin-gui"/>
<user username="tomcat" password="tomcat" roles="manager-gui,admin-gui"/>

tags用于让用户选择运行playbook中的部分代码。ansible具有幂等性,因此会自动跳过没有变化的部分,即便如此,有些代码为测试其确实没有发生变化的时间依然会非常地长。此时,如果确信其没有变化,就可以通过tags跳过此些代码片断。

示例:

  1. 在如下yaml文件中定义两个tags
 - hosts: tomcat
   remote_user: root
   tasks:
   - name: install tomcat-admin-webapps
     yum: name=tomcat-admin-webapps state=installed
   - name: install tomcat-users.xml
     copy: src=/root/ansible_workshop/tomcat-users.xml dest=/etc/tomcat/tomcat-users.xml owner=root group=tomcat mode=0640
     tags: tcusers
     notify: restart tomcat
   - name: install server.xml
     template: src=/root/ansible_workshop/server.xml.j2 dest=/etc/tomcat/server.xml owner=root group=tomcat
     notify: restart tomcat
     tags: serverconf
   - name: start tomcat
     service: name=tomcat state=started
   handlers:
   - name: restart tomcat
     service: name=tomcat state=restarted
  1. 测试观察
[root@nfs ansible_workshop]# ansible-playbook --check --tags=tcusers tomcat.yaml 

PLAY [tomcat] *************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np1.lxk.com]
ok: [np2.lxk.com]

TASK [install tomcat-users.xml] *******************************************************************************************
ok: [np2.lxk.com]
ok: [np1.lxk.com]

PLAY RECAP ****************************************************************************************************************
np1.lxk.com                : ok=2    changed=0    unreachable=0    failed=0   
np2.lxk.com                : ok=2    changed=0    unreachable=0    failed=0   

经测试,使用--tags指定tags之后,只运行了指定tags的任务。

条件测试:when语句:在task中使用,jinja2的语法格式
示例:当系统版本是7时,复制nginx.conf.c7.j2。系统版本是6时,复制nginx.conf.c6

tasks: 
- name: install conf file to centos7
  template: src=files/nginx.conf.c7.j2
  when: ansible_distribution_major_version == "7"
- name: install conf file to centos6
  template: src=files/nginx.conf.c6.j2
  when: ansible_distribution_major_version == "6"

循环:迭代,需要重复执行的任务;
对迭代项的引用,固定变量名为”item“,而后,要在task中使用with_items给定要迭代的元素列表;

- name: install some packages
  yum: name={{ item }} state=present            #item:固定字符,不能更改
  with_items:       #使用以下值给item赋值
  - nginx
  - memcached
  - php-fpm

- name: add some groups
  group: name={{ item }} state=present
  with_items:
  - group11
  - group12
  - group13

- name: add some users
  user: name={{ item.name }} group={{ item.group }} state=present
        #name={{ item.name }}  指明变量名
        #group={{ item.group}}  指明变量组
  with_items:
  - { name: 'user11', group: 'group11' }
  - { name: 'user12', group: 'group12' }
  - { name: 'user13', group: 'group13' }

示例:在目标主机上一次性安装三个包并启动起来

  1. 配置文件
- hosts: np1.lxk.com
  remote_user: root
  tasks:
  - name: install {{ item }}
    yum: name={{ item }} state=installed
    with_items:
    - nginx
    - memcached
    - php-fpm
  - name: start {{ item }}
    service: name={{ item }} state=started
    with_items:
    - nginx
    - memcached
    - php-fpm
  1. 运行:
[root@nfs ansible_workshop]# ansible-playbook nmp.yaml 

PLAY [np1.lxk.com] ********************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np1.lxk.com]

TASK [install {{ item }}] *************************************************************************************************
ok: [np1.lxk.com] => (item=[u'nginx', u'memcached', u'php-fpm'])

TASK [start {{ item }}] ***************************************************************************************************
changed: [np1.lxk.com] => (item=nginx)
ok: [np1.lxk.com] => (item=memcached)
ok: [np1.lxk.com] => (item=php-fpm)

PLAY RECAP ****************************************************************************************************************
np1.lxk.com                : ok=3    changed=1    unreachable=0    failed=0   

roles

ansilbe自1.2版本引入的新特性,用于层次性、结构化地组织playbook。roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单来讲,roles就是通过分别将变量、文件、任务、模板及处理器放置于单独的目录中,并可以便捷地include它们的一种机制。角色一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中。
一个roles的案例如下所示:

        site.yml
        webservers.yml
        dbservers.yml
        roles/
           common/
             files/
             templates/
             tasks/
             handlers/
             vars/
             meta/
           webservers/
             files/
             templates/
             tasks/
             handlers/
             vars/
             meta/

而在playbook中,可以这样使用roles:

    - hosts: webservers
      roles:
         - common
         - webservers

也可以向roles传递参数,例如:

    - hosts: webservers
      roles:
        - common
        - { role: foo_app_instance, dir: '/opt/a',  port: 5000 }
        - { role: foo_app_instance, dir: '/opt/b',  port: 5001 }

甚至也可以条件式地使用roles,例如:

    - hosts: webservers
      roles:
        - { role: some_role, when: "ansible_os_family == 'RedHat'" }

创建role的步骤

(1) 创建以roles命名的目录;
(2) 在roles目录中分别创建以各角色名称命名的目录,如webservers等;
(3) 在每个角色命名的目录中分别创建files、handlers、meta、tasks、templates和vars目录;用不到的目录可以创建为空目录,也可以不创建;
(4) 在playbook文件中,调用各角色;

role内各目录中可用的文件

tasks目录:至少应该包含一个名为main.yml的文件,其定义了此角色的任务列表;此文件可以使用include包含其它的位于此目录中的task文件;
files目录:存放由copy或script等模块调用的文件;
templates目录:template模块会自动在此目录中寻找Jinja2模板文件;
handlers目录:此目录中应当包含一个main.yml文件,用于定义此角色用到的各handler;在handler中使用include包含的其它的handler文件也应该位于此目录中;
vars目录:应当包含一个main.yml文件,用于定义此角色用到的变量;
meta目录:应当包含一个main.yml文件,用于定义此角色的特殊设定及其依赖关系;ansible 1.3及其以后的版本才支持;
default目录:为当前角色设定默认变量时使用此目录;应当包含一个main.yml文件;

示例1:安装nginx并为其提供配置文件和主页

  1. 创建所需目录:

/etc/ansible/role

[root@nfs roles]# mkdir -pv ./nginx/{files,templates,tasks,handlers,vars,meta,default}
  1. 提供所需配置文件:
    在/etc/ansible/roles/nginx目录下提供以下配置文件
[root@nfs nginx]# cat tasks/main.yml        #提供任务列表
- name: install epel-release package
  yum: name=epel-release state=installed
- name: install nginx package
  yum: name=nginx state=installed
- name: create doc root
  file: path={{ docroot }} state=directory
- name: install home page
  copy: src=index.html dest={{ docroot }}/
- name: install conf file
  template: src=server.conf.j2 dest=/etc/nginx/conf.d/server.conf
  notify: reload nginx
- name: start nginx service
  service: name=nginx enabled=true state=started

[root@nfs nginx]# cat vars/main.yml         #提供变量
docroot: /data/nginx/

[root@nfs nginx]# cat templates/server.conf.j2      #提供配置文件模板
server { 
    listen 80;
    server_name {{ ansible_fqdn }} {{ ansible_hostname }} ;

    location / {
        root {{ docroot }};
        index index.html index.jsp;
    }
}

[root@nfs nginx]# cat files/index.html      #提供主页
<h1> Welcome to Nginx</h1>

[root@nfs nginx]# cat handlers/main.yml         #提供条件式触发文件
- name: reload nginx
  service: name=nginx state=reloaded

在其它位置提供nginx.yaml文件:

[root@nfs ansible_workshop]# cat nginx.yaml 
- hosts: np1.lxk.com
  remote_user: root
  roles:
  - nginx
  1. 运行:
[root@nfs ansible_workshop]# ansible-playbook nginx.yaml 

PLAY [np1.lxk.com] ********************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************
ok: [np1.lxk.com]

TASK [nginx : install epel-release package] *******************************************************************************
changed: [np1.lxk.com]

TASK [nginx : install nginx package] **************************************************************************************
ok: [np1.lxk.com]

TASK [nginx : create doc root] ********************************************************************************************
changed: [np1.lxk.com]

TASK [nginx : install home page] ******************************************************************************************
changed: [np1.lxk.com]

TASK [nginx : install conf file] ******************************************************************************************
changed: [np1.lxk.com]

TASK [nginx : start nginx service] ****************************************************************************************
changed: [np1.lxk.com]

RUNNING HANDLER [nginx : reload nginx] ************************************************************************************
changed: [np1.lxk.com]

PLAY RECAP ****************************************************************************************************************
np1.lxk.com                : ok=8    changed=6    unreachable=0    failed=0   

示例2:

同示例1,修改以下内容:

  1. templates下增加proxy.conf.j2文件,内容如下:
[root@nfs nginx]# cat templates/proxy.conf.j2 
server {
    listen 80;
    server_name {{ ansible_fqdn }} {{ ansible_hostname }};
    location / {
        proxy_pass {{ backendurl }};
    }
}
  1. vars下main.yml修改为如下:
[root@nfs nginx]# cat vars/main.yml 
servertype: web
backendurl: 'http://127.0.0.1:8080'
docroot: /data/nginx/
  1. tasks下main.yml修改为如下:
[root@nfs nginx]# cat tasks/main.yml 
- name: install epel-release package
  yum: name=epel-release state=installed
- name: install nginx package
  yum: name=nginx state=installed
- name: create doc root
  file: path={{ docroot }} state=directory
  when: servertype == 'web'
- name: install home page
  copy: src=index.html dest={{ docroot }}/
  when: servertype == 'web'
- name: install web conf file
  template: src=server.conf.j2 dest=/etc/nginx/conf.d/server.conf
  when: servertype == 'web'
  notify: reload nginx
- name: install proxy conf file
  template: src=proxy.conf.j2 dest=/etc/nginx/conf.d/server.conf
  when: servertype == 'proxy'
  notify: reload nginx
- name: start nginx service
  service: name=nginx enabled=true state=started

4.nginx.yaml修改为如下:

[root@nfs nginx]# cat /root/ansible_workshop/nginx.yaml 
- hosts: tomcat
  remote_user: root
  roles:
  - { role: nginx, servertype: proxy }

- hosts: web
  remote_user: root
  roles:
  - nginx

猜你喜欢

转载自blog.51cto.com/11975865/2160674