22.1 ansible剧本playbook

http://galaxy.ansible.com       #ansible开源个人共享库
https://galaxy.ansible.com/explore#/
http://github.com/                    #ansible源代码
http://ansible.com.cn/               #马哥团队荣誉出品
https://github.com/ansible/ansible
https://github.com/ansible/ansible-examples

playbook由一个或者多个play组成的列表,playbook采用yaml语言
task是ansible中的一个个module模块。在playbook剧本中,按照事先规定的剧本中的一个个模块,剧情,来同唱一台大戏

    Hosts 执行的远程主机列表
    Tasks 任务集
    Varniables 内置变量或自定义变量在playbook中调用
    Templates 模板,可替换模板文件中的变量并实现一些简单逻辑的文件
    Handlers 和notity结合使用,由特定条件触发的操作,满足条件方才执行,否则不执行
    tags 标签 指定某条任务执行,用于选择运行playbook中的部分代码。ansible  具有幂等性,因此会自动跳过没有变化的部分,即便如此,有些代码为测试其  确实没有发生变化的时间依然会非常地长。此时,如果确信其没有变化,就可  以通过tags跳过此些代码片断
ansible-playbook –t tagsname useradd.yml

目录

#检查一下语法是否有误  -C测试

#再次执行,不会发生改变,幂等性

handler与notify

tags

playbook变量

主机清单中定义变量

摸版templates

when 条件判断

with_items 迭代


    [root@centos7:~]# ansible all -m yum -a 'name=httpd state=absent'
    [root@centos7:~]# mkdir ansible
    [root@centos7:~]# cd ansible

    [root@centos7:~]# cp /etc/httpd/conf/httpd.conf .
    [root@centos7:~]# vim httpd.conf
    Listen 8080  

    [root@centos7:ansible]# vim httpd.yml
    ---
    - hosts: appsrvs
      remote_user: root
    
      tasks:
       - name: isntall package
         yum: name=httpd
       - name: copy config
         copy: src=/root/httpd.conf dest=/etc/httpd/conf/
       - name: start service
         service: name=httpd state=started

#检查一下语法是否有误  -C测试

    [root@centos7:ansible]# ansible-playbook -C httpd.yml

    [root@centos7:ansible]# ansible-playbook httpd.yml

    PLAY [appsrvs] *********************************************************************************************

    TASK [Gathering Facts] *************************************************************************************
    ok: [192.168.31.27]
    ok: [192.168.31.17]

    TASK [isntall package] *************************************************************************************
    changed: [192.168.31.27]
    changed: [192.168.31.17]

    TASK [copy config] *****************************************************************************************
    changed: [192.168.31.27]
    changed: [192.168.31.17]

    TASK [start service] ***************************************************************************************
    changed: [192.168.31.27]
    changed: [192.168.31.17]

    PLAY RECAP *************************************************************************************************
    192.168.31.17              : ok=4    changed=3    unreachable=0    failed=0   
    192.168.31.27              : ok=4    changed=3    unreachable=0    failed=0


#再次执行,不会发生改变,幂等性

    [root@centos7:ansible]# ansible-playbook httpd.yml

    [root@centos7:ansible]# vim httpd.yml
    - hosts: appsrvs:websrvs   
    #centos6上执行失败
    [root@centos7:ansible]# ansible-playbook httpd.yml
    PLAY [appsrvs:websrvs] *************************************************************************************

    TASK [Gathering Facts] *************************************************************************************
    ok: [192.168.31.27]
    ok: [192.168.31.17]
    ok: [192.168.31.6]

    TASK [isntall package] *************************************************************************************
    ok: [192.168.31.27]
    ok: [192.168.31.17]
    changed: [192.168.31.6]

    TASK [copy config] *****************************************************************************************
    ok: [192.168.31.27]
    changed: [192.168.31.6]
    ok: [192.168.31.17]

    TASK [start service] ***************************************************************************************
    ok: [192.168.31.27]
    fatal: [192.168.31.6]: FAILED! => {"changed": false, "msg": "httpd: Syntax error on line 56 of /etc/httpd/conf/httpd.conf: Include directory '/etc/httpd/conf.modules.d' not found\n"}
    ok: [192.168.31.17]
        to retry, use: --limit @/root/ansible/httpd.retry

    PLAY RECAP *************************************************************************************************
    192.168.31.17              : ok=4    changed=0    unreachable=0    failed=0   
    192.168.31.27              : ok=4    changed=0    unreachable=0    failed=0   
    192.168.31.6               : ok=3    changed=2    unreachable=0    failed=1   


    [root@centos7:ansible]# cat user.yml
    ---
    - hosts: websrvs
      remote_user: root

      tasks:
       - name: create group
         group: name=nginx gid=80 system=yes
       - name: create user
         user: name=nginx uid=80 group=nginx shell=/sbin/nologin home=/data/ngnix system=yes comment="nginx user"

    [root@centos7:ansible]# ansible-playbook -C user.yml
    [root@centos7:ansible]# ansible websrvs -a 'getent passwd nginx'
    192.168.31.6 | SUCCESS | rc=0 >>
    nginx:x:80:80:nginx user:/data/ngnix:/sbin/nologin

    192.168.31.17 | SUCCESS | rc=0 >>
    nginx:x:80:80:nginx user:/data/ngnix:/sbin/nologin

    [root@centos7:ansible]# ansible websrvs -a 'ls /data'
    192.168.31.6 | SUCCESS | rc=0 >>
    ngnix
    testlink2.txt
    testlink.txt
    test.txt

    [root@centos7:ansible]# ansible websrvs -m user -a 'name=nginx remove=yes state=absent'

handler与notify

   [root@centos7:ansible]# cat httpd.yml
    ---
    - hosts: appsrvs
      remote_user: root
    
      tasks:
       - name: isntall package
         yum: name=httpd
       - name: copy config
         copy: src=/root/httpd.conf dest=/etc/httpd/conf/
         notify: restart service                   #通知
       - name: start service
         service: name=httpd state=started

      handlers:                                    #处理
       - name: restart service
         service: name=httpd state=restarted

    [root@centos7:ansible]# ansible-playbook -C httpd.yml

    [root@centos7:ansible]# vim /root/httpd.conf
    Listen 80

    [root@centos7:ansible]# ansible-playbook  httpd.yml

    RUNNING HANDLER [restart service] **************************************************************************
    changed: [192.168.31.27]
    changed: [192.168.31.17]


tags

 

   [root@centos7:~]# vim ansible/httpd.yml
    ---
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: isntall package
         yum: name=httpd
       - name: copy config
         copy: src=/root/httpd.conf dest=/etc/httpd/conf/
         tags: conf                                                                                             
         notify: restart service
       - name: start service
         service: name=httpd state=started
         tags: start
      handlers:
       - name: restart service
         service: name=httpd state=restarted
    #只执行conf所在的字典,即copy config,并且标签名可以相同,执行的时候,都会执行
    [root@centos7:ansible]# ansible-playbook -t conf httpd.yml
    [root@centos7:ansible]# ansible-playbook -t conf,start httpd.yml


playbook变量

    [root@centos7:ansible]# ansible-doc -s setup

    [root@centos7:ansible]# ansible all -m setup | grep name
    [root@centos7:~]# ansible all -m setup -a 'filter=ansible_nodename'
    192.168.31.6 | SUCCESS => {
        "ansible_facts": {
            "ansible_nodename": "centos6.dhy.com"
        },
        "changed": false
    }

    #操作系统的主版本号
    [root@centos7:~]# ansible all -m setup -a 'filter=*major*'
    192.168.31.6 | SUCCESS => {
        "ansible_facts": {
            "ansible_distribution_major_version": "6"
        },
        "changed": false
    }
    192.168.31.17 | SUCCESS => {
        "ansible_facts": {
            "ansible_distribution_major_version": "7"
        },
        "changed": false
    }
    变量ansible_distribution_major_version

    #内存
    [root@centos7:~]# ansible all -m setup -a 'filter=*mb*'
        "ansible_memtotal_mb": 974,
        "ansible_swapfree_mb": 0,
        "ansible_swaptotal_mb": 0
    --------------------------------------------
    #变量
    [root@centos7:ansible]# cat var1.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: install package
         yum: name={{ pname }}            #变量{{ pname }}
    [root@centos7:ansible]# ansible-playbook -e pname=vsftpd var1.yml
    [root@centos7-1:~]# yum history info 22
    ----------------------------------------------
    [root@centos7:ansible]# cat var1.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: install package
         yum: name={{ pname }}    #变量
         tags: install            
       - name: remove package
         yum: name={{ pname }} state=absent    #
         tags: remove              #

    [root@centos7:ansible]# ansible-playbook -t remove -e pname=vsftpd var1.yml
    ----------------------------------------------------
    [root@centos7:ansible]# cat var1.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: install package
         yum: name={{ pname1 }}
         tags: install              #标签可以重名
       - name: install package2
         yum : name={{ pname2 }}
         tags: install              #标签可以重名
       - name: remove package
         yum: name={{ pname }} state=absent
         tags: remove
    [root@centos7:ansible]# ansible-playbook -t install -e "pname1=vsftpd pname2=samba" var1.yml

    --------------------------------------------
    [root@centos7:ansible]# cat var1.yml
    - hosts: appsrvs
      remote_user: root
      vars:
        - pname1: vsftpd      #定义变量
        - pname2: samba

      tasks:
       - name: install package
         yum: name={{ pname1 }}
         tags: install              
       - name: install package2
         yum : name={{ pname2 }}
         tags: install              
       - name: remove package
         yum: name={{ pname }} state=absent
         tags: remove

    [root@centos7:ansible]# ansible-playbook -t remove -e "pname=vsftpd" var1.yml
    [root@centos7:ansible]# ansible-playbook -t remove -e "pname=samba" var1.yml
    [root@centos7:ansible]# ansible-playbook -t install  var1.yml
    ---------------------------------------------------------------------
    # 命令行的优先级高于配置文件中的变量
    [root@centos7:ansible]# ansible-playbook -t install -e "pname1=memcached pname2=screen" var1.yml
    
    [root@centos7-1:~]# yum history
    Loaded plugins: fastestmirror, langpacks
    ID     | Command line             | Date and time    | Action(s)      | Altered
    -------------------------------------------------------------------------------
        33 | -d 2 -y install screen   | 2018-07-29 19:27 | Install        |    1

    ——————————————————————————————————————————————————
    #定义变量文件         

    [root@centos7:ansible]# vim vars.yml
    pname1: samba
    pname2: vsftpd   

    [root@centos7:ansible]# cat var1.yml
    - hosts: appsrvs
      remote_user: root
      vars_files:               #引用变量文件
       - vars.yml

      tasks:
       - name: install package
         yum: name={{ pname1 }}
         tags: install
       - name: install package2
         yum : name={{ pname2 }}
         tags: install
       - name: remove package
         yum: name={{ pname }} state=absent
         tags: remove

    [root@centos7:ansible]# ansible-playbook -t  install var1.yml

 ————————————————————————————————————————————————————————

主机清单中定义变量

    [root@centos7:~]# vim /etc/ansible/hosts
    [appsrvs]
    192.168.31.17 http_port=81              #主机清单定义变量
    192.168.31.27 http_port=82
    [root@centos7:ansible]# pwd
    /root/ansible
    [root@centos7:ansible]# vim var2.yml
    [root@centos7:ansible]# cat var2.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: change hostname
         hostname: name=web-{{http_port}}.dhy.com
    [root@centos7:ansible]# ansible-playbook var2.yml
    [root@centos7-1:~]# hostname
    web-81.dhy.com
    [root@centos7-2:~ ]# hostname
    web-82.dhy.com
    ---------------------------------------------
    [root@centos7:~]# vim /etc/ansible/hosts
    [appsrvs]
    192.168.31.17 hname=web1 http_port=81     #主机清单中定义两个变量
    192.168.31.27 hname=web2 http_port=82
    [root@centos7:ansible]# cat var2.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: change hostname
         hostname: name={{hname}}-{{http_port}}.dhy.com    #引用变量
    [root@centos7:ansible]# ansible-playbook var2.yml
    [root@centos7-1:~]# hostname
    web1-81.dhy.com
    [root@centos7-2:~ ]# hostname
    web2-82.dhy.com


    -------------------------------------
    [root@centos7:~]# vim /etc/ansible/hosts
    [appsrvs]
    192.168.31.17 hname=web1 http_port=81
    192.168.31.27 hname=web2 http_port=82

    [appsrvs:vars]
    mark='_'                                 #通用变量

    [root@centos7:ansible]# cat var2.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: change hostname
         hostname: name={{hname}}{{mark}}{{http_port}}.dhy.com  #引用通用变量
    [root@centos7-1:~]# hostname
    web1_81.dhy.com
    [root@centos7-2:~ ]# hostname
    web2_82.dhy.com
    -----------------------------------------------
    #文件中的变量优先级高于主机清单中变量的优先级;命令中的优先级最高
    [root@centos7:ansible]# cat var2.yml
    - hosts: appsrvs
      remote_user: root
      vars:                        #文件中定义变量,另主机清单中也有变量
       - hname: websrv
       - mark: -
      tasks:
       - name: change hostname
         hostname: name={{hname}}{{mark}}{{http_port}}.dhy.com

    [root@centos7:ansible]# ansible-playbook var2.yml
    [root@centos7-1:~]# hostname
    websrv-81.dhy.com

    ----------------------
    [root@centos7:~]# vim /etc/ansible/hosts
    [appsrvs]
    192.168.31.17 hname=web1 http_port=81 mark='-'  #优先级高于组变量
    192.168.31.27 hname=web2 http_port=82

    [appsrvs:vars]                                  #组变量
    mark='_'
    -------------------------


摸版templates

    copy拷贝文件,都是一样的,如果要实现拷贝到不同的远程主机上的文件不相同,则需要摸版template

        文本文件,嵌套有脚本(使用模板编程语言编写) 
        Jinja2语言,使用字面量,有下面形式  
            字符串:使用单引号或双引号
            数字:整数,浮点数
            列表:[item1, item2, ...]
            元组:(item1, item2, ...)
            字典:{key1:value1, key2:value2, ...}
            布尔型:true/false
        算术运算:+, -, *, /, //, %, ** 
        比较操作:==, !=, >, >=, <, <= 
        逻辑运算:and, o r, not 
        流表达式:For If When


        templates功能:根据模块文件动态生成对应的配置文件
        templates文件必须存放于templates目录下,且命名为 .j2 结尾 
        yaml/yml 文件需和templates目录平级,目录结构如下:
            ./
            ├── temnginx.yml
            └── templates
                └── nginx.conf.j2 

   [root@centos7:ansible]# pwd
    /root/ansible
    [root@centos7:ansible]# mkdir templates
    [root@centos7:ansible]# tree
    .
    ├── httpd.retry
    ├── httpd.yml
    ├── templates
    ├── user.yml
    ├── var1.yml
    ├── var2.yml
    └── vars.yml
    1 directory, 6 files

[root@centos7:ansible]# yum install nginx
[root@centos7:ansible]# rpm -ql nginx
安装nginx服务,centos7-1,centos7-2 两个主机都是2个cpu,把centos7-2的cpu改为4个。下面实现ansible安装nginx时,根据cpu个数生成对应cpu个数2倍的线程数
    [root@websrv-82:~ ]# lscpu
    CPU(s):                4
    [root@centos7-1:~]# lscpu
    CPU(s):                2

    [root@centos7:ansible]# cat nginx.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: install package     #name和yum对齐
         yum: name=nginx
       - name: start
         service: name=nginx state=started
 
    #nginx服务没有启动
    [root@centos7-1:~]# ps aux |grep nginx
    root      52839  0.0  0.0 112704   972 pts/1    S+   20:21   0:00 grep --color=auto nginx
    #默认cpu个数个work process
    [root@websrv-82:~ ]# ps aux |grep nginx
    root       2180  0.0  0.1 122908  2236 ?        Ss   20:33   0:00 nginx: master process /usr/sbin/nginx
    nginx      2181  0.0  0.3 125376  3552 ?        S    20:33   0:00 nginx: worker process
    nginx      2182  0.0  0.3 125376  3552 ?        S    20:33   0:00 nginx: worker process
    nginx      2183  0.0  0.3 125376  3552 ?        S    20:33   0:00 nginx: worker process
    nginx      2184  0.0  0.3 125376  3552 ?        S    20:33   0:00 nginx: worker process
    root       2206  0.0  0.0 112660   968 pts/0    S+   20:33   0:00 grep --color=auto nginx

    
    [root@centos7:ansible]# ansible all -m setup | grep cpu
        "ansible_processor_vcpus": 4,
        "ansible_processor_vcpus": 2,
        "ansible_processor_vcpus": 2,
    [root@centos7:ansible]# vim templates/nginx.conf.j2
    由auto改为变量
    worker_processes {{ansible_processor_vcpus*2}};  

    [root@centos7:ansible]# ansible appsrvs -m yum -a 'name=nginx state=absent'


    [root@centos7:ansible]# vim nginx.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: install package
         yum: name=nginx
       - name: template
         template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf                                                 
       - name: start
         service: name=nginx state=started

    [root@centos7:ansible]# ansible-playbook nginx.yml
    #4个线程 work process状态
    [root@centos7-1:~]# ps aux |grep nginx
    root      56559  0.0  0.2 107968  2136 ?        Ss   20:52   0:00 nginx: master process /usr/sbin/nginx
    nginx     56560  0.0  0.3 110472  3416 ?        S    20:52   0:00 nginx: worker process
    nginx     56561  0.0  0.3 110472  3416 ?        S    20:52   0:00 nginx: worker process
    nginx     56562  0.0  0.3 110472  3416 ?        S    20:52   0:00 nginx: worker process
    nginx     56563  0.0  0.3 110472  3416 ?        S    20:52   0:00 nginx: worker process
    root      56581  0.0  0.0 112704   972 pts/1    R+   20:52   0:00 grep --color=auto nginx
    #8个线程 work process状态
    [root@websrv-82:~ ]# ps aux |grep nginx
    root       4063  0.0  0.1 122908  2244 ?        Ss   20:52   0:00 nginx: master process /usr/sbin/nginx
    nginx      4064  0.0  0.3 125376  3568 ?        S    20:52   0:00 nginx: worker process
    nginx      4065  0.0  0.3 125376  3568 ?        S    20:52   0:00 nginx: worker process
    nginx      4066  0.0  0.3 125376  3568 ?        S    20:52   0:00 nginx: worker process
    nginx      4067  0.0  0.3 125376  3568 ?        S    20:52   0:00 nginx: worker process
    nginx      4068  0.0  0.3 125376  3568 ?        S    20:52   0:00 nginx: worker process
    nginx      4069  0.0  0.3 125376  3568 ?        S    20:52   0:00 nginx: worker process
    nginx      4070  0.0  0.3 125376  3568 ?        S    20:52   0:00 nginx: worker process
    nginx      4071  0.0  0.3 125376  3568 ?        S    20:52   0:00 nginx: worker process
    root       4091  0.0  0.0 112660   968 pts/0    R+   20:52   0:00 grep --color=auto nginx
    ---------------------------------------------------------------
    [root@centos7:ansible]# vim templates/nginx.conf.j2
    server {
        listen       {{http_port}} default_server;

    [root@centos7:ansible]# vim /etc/ansible/hosts
    [appsrvs]
    192.168.31.17 hname=web1 http_port=81
    192.168.31.27 hname=web2 http_port=82

    [appsrvs:vars]
    mark='_'
    [root@centos7:ansible]# ansible appsrvs -m yum -a 'name=nginx state=absent'
    #摸版中的端口号80改为了变量,而变量定义在主机清单中,nginx.yml无需改动


    [root@centos7-1:~]# ss -ntl
    LISTEN     0      128                *:81        *:*  
    [root@websrv-82:~ ]# ss -ntl
    LISTEN     0      128                *:82         *:*
    ---------------------------------
    #改成83
    [root@centos7:ansible]# cat nginx.yml
    - hosts: appsrvs
      remote_user: root
      vars:
       - http_port: 83
      tasks:
       - name: install package
         yum: name=nginx
       - name: template
         template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
       - name: start
         service: name=nginx state=started

    [root@centos7:ansible]# ansible appsrvs -m yum -a 'name=nginx state=absent'
    [root@centos7-1:~]# ss -ntl
    LISTEN     0      128         *:83             *:*
    [root@websrv-82:~ ]# ss -ntl
    LISTEN     0      128         *:83             *:*
    --------------------------------------------

when 条件判断

    #httpd服务利用ansible安装到centos6和centos7上,由于6和7配置文件不同,需要条件判断
    [root@centos7:ansible]# scp 192.168.31.6:/etc/httpd/conf/httpd.conf templates/httpd.conf6.j2
    /root/.bashrc: line 8: aliaz: command not found
    httpd.conf                                    100%   11KB   8.3MB/s   00:00
    #主版本号变量
    [root@centos7:ansible]# ansible all -m setup -a "filter=*major*"
    192.168.31.6 | SUCCESS => {
        "ansible_facts": {
            "ansible_distribution_major_version": "6"

    [root@centos7:ansible]# cat templatehttpd.yml
    - hosts: all
      remote_user: root

      tasks:
       - name: install package
         yum: name=httpd
       - name: copy template file
         template: src=httpd.conf6.j2 dest=/etc/httpd/conf/httpd.conf
         when: ansible_distribution_major_version == '6'
       - name: start
         service: name=httpd state=started

    [root@centos7:ansible]# cp /etc/httpd/conf/httpd.conf templates/httpd.conf7.j2
    #端口号改为9527
    [root@centos7:ansible]# vim templates/httpd.conf6.j2
    Listen 9527  
    [root@centos7:ansible]# ansible-playbook templatehttpd.yml
    TASK [copy template file] **********************************************************************************
    skipping: [192.168.31.17]
    skipping: [192.168.31.27]
    changed: [192.168.31.6]

with_items 迭代

    [root@centos7:ansible]# cat templatecopy.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: copy files
         copy: src={{item}} dest=/data/
         with_items:
          - file1
          - file2
          - file3
    [root@centos7:ansible]# mkdir files
    [root@centos7:ansible]# touch files/file{1,2,3}
    [root@centos7:ansible]# tree
    [root@centos7:ansible]# tree
    .
    ├── files
    │   ├── file1
    │   ├── file2
    │   └── file3
    ├── httpd.yml
    ├── nginx.yml
    ├── templatehttpd.retry
    ├── templatehttpd.yml
    ├── templates
    │   ├── httpd.conf6.j2
    │   ├── httpd.conf7.j2
    │   └── nginx.conf.j2
    ├── user.yml
    ├── var1.yml
    ├── var2.yml
    └── vars.yml
    2 directories, 14 files

    #把f1,f2,f3文件拷贝到远程主机
    [root@centos7:ansible]# ansible-playbook templatecopy.yml
    TASK [copy files] ******************************************************************************************
    changed: [192.168.31.27] => (item=file1)
    changed: [192.168.31.17] => (item=file1)
    changed: [192.168.31.27] => (item=file2)
    changed: [192.168.31.17] => (item=file2)
    changed: [192.168.31.27] => (item=file3)
    changed: [192.168.31.17] => (item=file3)
    -----------------------------------------------
    [root@centos7:ansible]# cat batchusers.yml
    - hosts: appsrvs
      remote_user:

      tasks:
       - name: create user
         user: naem={{item}}
         with_items:
          - tom
          - jerry
          - duck
          - dog
    [root@centos7:ansible]# ansible-playbook -C batchusers.yml
    [root@websrv-82:~ ]# for i in tom jerry duck dog;do userdel -r $i;done
    -------------------------------------------------------------------
    [root@centos7:ansible]# cat batchusers.yml
    - hosts: appsrvs
      remote_user: root

      tasks:
       - name: create user
         group: name={{item}}
         with_items:
          - g1
          - g2
          - g3
          - g4
       - name: create user
         user: name={{item.name}} group={{item.group}}
         with_items:
          - {name: 'tom',group: 'g1'}
          - {name: 'jerry',group: 'g2'}
          - {name: 'duck',group: 'g3'}
          - {name: 'cat',group: 'g4'}

    [root@centos7:ansible]# ansible-playbook batchusers.yml
    ------------------------------------------------

playbook中的template for if
    [root@centos7:ansible]# cat templates/for.j2
    {% for port in ports %}
    server {
        listen {{port}}
    }
    {%endfor%}
    [root@centos7:ansible]# cat templatefor.yml
    - hosts: appsrvs
      remote_user: root
      vars:
       ports:
        - 81
        - 82
        - 83

       tasks:
        - name: conf
          template: src=for.j2 dest=/data/for.conf

    [root@centos7:ansible]# ansible-playbook templatefor.yml
    [root@centos7-1:~]# ls /data
    file1  file2  file3  testlink2.txt  testlink.txt  test.txt


    [root@centos7:ansible]# tree
    .
    ├── batchusers.yml
    ├── files
    │   ├── file1
    │   ├── file2
    │   └── file3
    ├── httpd.yml
    ├── nginx.yml
    ├── templatecopy.yml
    ├── templatefor.yml
    ├── templatehttpd.retry
    ├── templatehttpd.yml
    ├── templates
    │   ├── for.j2
    │   ├── httpd.conf6.j2
    │   ├── httpd.conf7.j2
    │   └── nginx.conf.j2
    ├── user.yml
    ├── var1.yml
    ├── var2.yml
    └── vars.yml
    2 directories, 18 files

    ------------------------------------------------------------------
    [root@centos7:ansible]# cp templatefor.yml templatefor2.yml
    [root@centos7:ansible]# cat templates/for2.j2
    {% for host in vhosts %}
    server {
        server {{host.fqdn}}
        root {{host.dataroot}}
        listen {{host.port}}
    }
    {%endfor%}
    [root@centos7:ansible]# cat templatefor2.yml
    - hosts: appsrvs
      remote_user: root
      vars:
       vhosts:
        - web1:
          fqdn: www.a.com
          dataroot: /data/sitea
          port: 81
        - web2:
          fqdn: www.b.com
          dataroot: /data/siteb
          port: 82
        - web3:
          fqdn: www.c.com
          dataroot: /data/sitec
          port: 83

      tasks:
        - name: conf
          template: src=for2.j2 dest=/data/for2.conf


    [root@centos7:ansible]# ansible-playbook templatefor2.yml
     [WARNING]: Found variable using reserved name: tasks
     #报错原因是tasks和hosts没对齐

    PLAY [appsrvs] *********************************************************************************************

    TASK [Gathering Facts] *************************************************************************************
    ok: [192.168.31.27]
    ok: [192.168.31.17]

    PLAY RECAP *************************************************************************************************
    192.168.31.17              : ok=1    changed=0    unreachable=0    failed=0   
    192.168.31.27              : ok=1    changed=0    unreachable=0    failed=0

    [root@centos7:ansible]# ansible-playbook -C templatefor2.yml
    [root@centos7-1:data]# cat /data/for2.conf
    server {
        server www.a.com
        root /data/sitea
        listen 81
    }
    server {
        server www.b.com
        root /data/siteb
        listen 82
    }
    server {
        server www.c.com
        root /data/sitec
        listen 83
    }
    --------------if----------------------
    [root@centos7:ansible]# cp templatefor2.yml templateif.yml
    [root@centos7:ansible]# cp templates/for2.j2 templates/for3.j2

    [root@centos7:ansible]# cat templateif.yml
    - hosts: appsrvs
      remote_user: root
      vars:
       vhosts:
        - web1:
         #fqdn: www.a.com
          dataroot: /data/sitea
          port: 81
        - web2:
          fqdn: www.b.com
          dataroot: /data/siteb
          port: 82
        - web3:
          #fqdn: www.c.com
          dataroot: /data/sitec
          port: 83

      tasks:
        - name: conf
          template: src=for3.j2 dest=/data/for3.conf

    [root@centos7:ansible]# cat templates/for3.j2
    {% for host in vhosts %}
    server {
    {% if host.fqdn is defined %}
        server {{host.fqdn}}
    {%endif%}
        root {{host.dataroot}}
        listen {{host.port}}
    }
    {%endfor%}

    [root@centos7:ansible]# ansible-playbook -C templatefor2.yml
    [root@centos7-1:data]# cat for3.conf
    server {
        root /data/sitea
        listen 81
    }
    server {
        server www.b.com
        root /data/siteb
        listen 82
    }
    server {
        root /data/sitec
        listen 83
    }

    [root@centos7:ansible]# tree
    .
    ├── batchusers.yml
    ├── files
    │   ├── file1
    │   ├── file2
    │   └── file3
    ├── httpd.yml
    ├── nginx.yml
    ├── templatecopy.yml
    ├── templatefor2.yml
    ├── templatefor.yml
    ├── templatehttpd.retry
    ├── templatehttpd.yml
    ├── templateif.yml
    ├── templates
    │   ├── for2.j2
    │   ├── for3.j2
    │   ├── for.j2
    │   ├── httpd.conf6.j2
    │   ├── httpd.conf7.j2
    │   └── nginx.conf.j2
    ├── user.yml
    ├── var1.yml
    ├── var2.yml
    └── vars.yml
    2 directories, 22 files

 

你可能感兴趣的:(linux)