Ansible--Ansible之Playbook

Ansible之Playbook

Playbook介紹

playbook參考文檔html

Playbookad-hoc相比,是一種徹底不一樣的運用ansible的方式,相似與saltstackstate狀態文件。ad-hoc沒法持久使用,playbook能夠持久使用。
playbook是由一個或多個play組成的列表,play的主要功能在於將事先歸併爲一組的主機裝扮成事先經過ansible中的task定義好的角色。從根本上來說,所謂的task無非是調用ansible的一個module。將多個play組織在一個playbook中,便可以讓它們聯合起來按事先編排的機制完成某一任務linux

Playbook核心元素

  • Hosts 執行的遠程主機列表
  • Tasks 任務集
  • Varniables 內置變量或自定義變量在playbook中調用
  • Templates 模板,即便用模板語法的文件,好比配置文件等
  • Handlers 和notity結合使用,由特定條件觸發的操做,知足條件方纔執行,不然不執行
  • tags 標籤,指定某條任務執行,用於選擇運行playbook中的部分代碼。

Playbook語法

playbook使用yaml語法格式,後綴能夠是yaml,也能夠是ymlnginx

  • 在單一一個playbook文件中,能夠連續三個連子號(---)區分多個play。還有選擇性的連續三個點好(...)用來表示play的結尾,也可省略。
  • 次行開始正常寫playbook的內容,通常都會寫上描述該playbook的功能。
  • 使用#號註釋代碼。
  • 縮進必須統一,不能空格和tab混用。
  • 縮進的級別也必須是一致的,一樣的縮進表明一樣的級別,程序判別配置的級別是經過縮進結合換行實現的。
  • YAML文件內容和Linux系統大小寫判斷方式保持一致,是區分大小寫的,k/v的值均需大小寫敏感
  • k/v的值可同行寫也能夠換行寫。同行使用:分隔。
  • v能夠是個字符串,也能夠是一個列表
  • 一個完整的代碼塊功能須要最少元素包括 name: task

一個簡單的示例

# 建立playbook文件
[root@ansible ~]# cat playbook01.yml
---                       #固定格式
- hosts: 192.168.1.31     #定義須要執行主機
  remote_user: root       #遠程用戶
  vars:                   #定義變量
    http_port: 8088       #變量

  tasks:                             #定義一個任務的開始
    - name: create new file          #定義任務的名稱
      file: name=/tmp/playtest.txt state=touch   #調用模塊,具體要作的事情
    - name: create new user
      user: name=test02 system=yes shell=/sbin/nologin
    - name: install package
      yum: name=httpd
    - name: config httpd
      template: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
      notify:                 #定義執行一個動做(action)讓handlers來引用執行,與handlers配合使用
        - restart apache      #notify要執行的動做,這裏必須與handlers中的name定義內容一致
    - name: copy index.html
      copy: src=/var/www/html/index.html dest=/var/www/html/index.html
    - name: start httpd
      service: name=httpd state=started
  handlers:                                    #處理器:更加tasks中notify定義的action觸發執行相應的處理動做
    - name: restart apache                     #要與notify定義的內容相同
      service: name=httpd state=restarted      #觸發要執行的動做

#測試頁面準備
[root@ansible ~]# echo "<h1>playbook test file</h1>" >>/var/www/html/index.html
#配置文件準備
[root@ansible ~]# cat httpd.conf |grep ^Listen
Listen {{ http_port }}

#執行playbook, 第一次執行能夠加-C選項,檢查寫的playbook是否ok
[root@ansible ~]# ansible-playbook playbook01.yml
PLAY [192.168.1.31] *********************************************************************************************
TASK [Gathering Facts] ******************************************************************************************
ok: [192.168.1.31]
TASK [create new file] ******************************************************************************************
changed: [192.168.1.31]
TASK [create new user] ******************************************************************************************
changed: [192.168.1.31]
TASK [install package] ******************************************************************************************
changed: [192.168.1.31]
TASK [config httpd] *********************************************************************************************
changed: [192.168.1.31]
TASK [copy index.html] ******************************************************************************************
changed: [192.168.1.31]
TASK [start httpd] **********************************************************************************************
changed: [192.168.1.31]
PLAY RECAP ******************************************************************************************************
192.168.1.31               : ok=7    changed=6    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 


# 驗證上面playbook執行的結果
[root@ansible ~]# ansible 192.168.1.31 -m shell -a 'ls /tmp/playtest.txt && id test02'
192.168.1.31 | CHANGED | rc=0 >>
/tmp/playtest.txt
uid=990(test02) gid=985(test02) 組=985(test02)

[root@ansible ~]# curl 192.168.1.31:8088
<h1>playbook test file</h1>

Playbook的運行方式

經過ansible-playbook命令運行
格式:ansible-playbook <filename.yml> ... [options]git

[root@ansible PlayBook]# ansible-playbook -h
#ansible-playbook經常使用選項:
--check  or -C    #只檢測可能會發生的改變,但不真正執行操做
--list-hosts      #列出運行任務的主機
--list-tags       #列出playbook文件中定義全部的tags
--list-tasks      #列出playbook文件中定義的因此任務集
--limit           #主機列表 只針對主機列表中的某個主機或者某個組執行
-f                #指定併發數,默認爲5個
-t                #指定tags運行,運行某一個或者多個tags。(前提playbook中有定義tags)
-v                #顯示過程  -vv  -vvv更詳細

Playbook中元素屬性

主機與用戶

在一個playbook開始時,最早定義的是要操做的主機和用戶github

---
- hosts: 192.168.1.31
  remote_user: root

除了上面的定義外,還能夠在某一個tasks中定義要執行該任務的遠程用戶web

tasks: 
  - name: run df -h
    remote_user: test
    shell: name=df -h

還能夠定義使用sudo受權用戶執行該任務shell

tasks: 
  - name: run df -h
    sudo_user: test
    sudo: yes
    shell: name=df -h

tasks任務列表

每個task必須有一個名稱name,這樣在運行playbook時,從其輸出的任務執行信息中能夠很清楚的辨別是屬於哪個task的,若是沒有定義 nameaction的值將會用做輸出信息中標記特定的task
每個playbook中能夠包含一個或者多個tasks任務列表,每個tasks完成具體的一件事,(任務模塊)好比建立一個用戶或者安裝一個軟件等,在hosts中定義的主機或者主機組都將會執行這個被定義的tasksapache

tasks:
  - name: create new file
    file: path=/tmp/test01.txt state=touch
  - name: create new user
    user: name=test001 state=present

Handlers與Notify

不少時候當咱們某一個配置發生改變,咱們須要重啓服務,(好比httpd配置文件文件發生改變了)這時候就能夠用到handlersnotify了;
(當發生改動時)notify actions會在playbook的每個task結束時被觸發,並且即便有多個不一樣task通知改動的發生,notify actions知會被觸發一次;好比多個resources指出由於一個配置文件被改動,因此apache須要重啓,可是從新啓動的操做知會被執行一次。vim

[root@ansible ~]# cat httpd.yml 
#用於安裝httpd並配置啓動
---
- hosts: 192.168.1.31
  remote_user: root

  tasks:
  - name: install httpd
    yum: name=httpd state=installed
  - name: config httpd
    template: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
    notify:
      - restart httpd
  - name: start httpd
    service: name=httpd state=started

  handlers:
    - name: restart httpd
      service: name=httpd state=restarted

#這裏只要對httpd.conf配置文件做出了修改,修改後須要重啓生效,在tasks中定義了restart httpd這個action,而後在handlers中引用上面tasks中定義的notify。

Playbook中變量的使用

環境說明:這裏配置了兩個組,一個apache組和一個nginx組centos

[root@ansible PlayBook]# cat /etc/ansible/hosts
[apache]
192.168.1.36
192.168.1.33

[nginx]
192.168.1.3[1:2]

命令行指定變量

執行playbook時候經過參數-e傳入變量,這樣傳入的變量在整個playbook中均可以被調用,屬於全局變量

[root@ansible PlayBook]# cat variables.yml 
---
- hosts: all
  remote_user: root

  tasks:
    - name: install pkg
      yum: name={{ pkg }}

#執行playbook 指定pkg
[root@ansible PlayBook]# ansible-playbook -e "pkg=httpd" variables.yml

hosts文件中定義變量

/etc/ansible/hosts文件中定義變量,能夠針對每一個主機定義不一樣的變量,也能夠定義一個組的變量,而後直接在playbook中直接調用。注意,組中定義的變量沒有單個主機中的優先級高。

# 編輯hosts文件定義變量
[root@ansible PlayBook]# vim /etc/ansible/hosts
[apache]
192.168.1.36 webdir=/opt/test     #定義單個主機的變量
192.168.1.33
[apache:vars]      #定義整個組的統一變量
webdir=/web/test

[nginx]
192.168.1.3[1:2]
[nginx:vars]
webdir=/opt/web


# 編輯playbook文件
[root@ansible PlayBook]# cat variables.yml 
---
- hosts: all
  remote_user: root

  tasks:
    - name: create webdir
      file: name={{ webdir }} state=directory   #引用變量


# 執行playbook
[root@ansible PlayBook]# ansible-playbook variables.yml

playbook文件中定義變量

編寫playbook時,直接在裏面定義變量,而後直接引用,能夠定義多個變量;注意:若是在執行playbook時,又經過-e參數指定變量的值,那麼會以-e參數指定的爲準。

# 編輯playbook
[root@ansible PlayBook]# cat variables.yml 
---
- hosts: all
  remote_user: root
  vars:                #定義變量
    pkg: nginx         #變量1
    dir: /tmp/test1    #變量2

  tasks:
    - name: install pkg
      yum: name={{ pkg }} state=installed    #引用變量
    - name: create new dir
      file: name={{ dir }} state=directory   #引用變量


# 執行playbook
[root@ansible PlayBook]# ansible-playbook variables.yml

# 若是執行時候又從新指定了變量的值,那麼會已從新指定的爲準
[root@ansible PlayBook]# ansible-playbook -e "dir=/tmp/test2" variables.yml

調用setup模塊獲取變量

setup模塊默認是獲取主機信息的,有時候在playbook中須要用到,因此能夠直接調用。經常使用的參數參考

# 編輯playbook文件
[root@ansible PlayBook]# cat variables.yml 
---
- hosts: all
  remote_user: root

  tasks:
    - name: create file
      file: name={{ ansible_fqdn }}.log state=touch   #引用setup中的ansible_fqdn


# 執行playbook
[root@ansible PlayBook]# ansible-playbook variables.yml

獨立的變量YAML文件中定義

爲了方便管理將全部的變量統一放在一個獨立的變量YAML文件中,laybook文件直接引用文件調用變量便可。

# 定義存放變量的文件
[root@ansible PlayBook]# cat var.yml 
var1: vsftpd
var2: httpd

# 編寫playbook
[root@ansible PlayBook]# cat variables.yml 
---
- hosts: all
  remote_user: root
  vars_files:    #引用變量文件
    - ./var.yml   #指定變量文件的path(這裏能夠是絕對路徑,也能夠是相對路徑)

  tasks:
    - name: install package
      yum: name={{ var1 }}   #引用變量
    - name: create file
      file: name=/tmp/{{ var2 }}.log state=touch   #引用變量


# 執行playbook
[root@ansible PlayBook]# ansible-playbook  variables.yml

Playbook中標籤的使用

一個playbook文件中,執行時若是想執行某一個任務,那麼能夠給每一個任務集進行打標籤,這樣在執行的時候能夠經過-t選擇指定標籤執行,還能夠經過--skip-tags選擇除了某個標籤外所有執行等。

# 編輯playbook
[root@ansible PlayBook]# cat httpd.yml 
---
- hosts: 192.168.1.31
  remote_user: root

  tasks:
    - name: install httpd
      yum: name=httpd state=installed
      tags: inhttpd

    - name: start httpd
      service: name=httpd state=started
      tags: sthttpd

    - name: restart httpd
      service: name=httpd state=restarted
      tags: 
        - rshttpd
        - rs_httpd

# 正常執行的結果
[root@ansible PlayBook]# ansible-playbook httpd.yml 

PLAY [192.168.1.31] **************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [192.168.1.31]

TASK [install httpd] *************************************************************************************************************************
ok: [192.168.1.31]

TASK [start httpd] ***************************************************************************************************************************
ok: [192.168.1.31]

TASK [restart httpd] *************************************************************************************************************************
changed: [192.168.1.31]

PLAY RECAP ***********************************************************************************************************************************
192.168.1.31               : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

1)經過-t選項指定tags進行執行

# 經過-t指定tags名稱,多個tags用逗號隔開
[root@ansible PlayBook]# ansible-playbook -t rshttpd httpd.yml 

PLAY [192.168.1.31] **************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [192.168.1.31]

TASK [restart httpd] *************************************************************************************************************************
changed: [192.168.1.31]

PLAY RECAP ***********************************************************************************************************************************
192.168.1.31               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

2)經過--skip-tags選項排除不執行的tags

[root@ansible PlayBook]# ansible-playbook --skip-tags inhttpd httpd.yml 

PLAY [192.168.1.31] **************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [192.168.1.31]

TASK [start httpd] ***************************************************************************************************************************
ok: [192.168.1.31]

TASK [restart httpd] *************************************************************************************************************************
changed: [192.168.1.31]

PLAY RECAP ***********************************************************************************************************************************
192.168.1.31               : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Playbook中模板的使用

template模板爲咱們提供了動態配置服務,使用jinja2語言,裏面支持多種條件判斷、循環、邏輯運算、比較操做等。其實說白了也就是一個文件,和以前配置文件使用copy同樣,只是使用copy,不能根據服務器配置不同進行不一樣動態的配置。這樣就不利於管理。
說明:
一、多數狀況下都將template文件放在和playbook文件同級的templates目錄下(手動建立),這樣playbook文件中能夠直接引用,會自動去找這個文件。若是放在別的地方,也能夠經過絕對路徑去指定。
二、模板文件後綴名爲.j2

循環參考

示例:經過template安裝httpd

1)playbook文件編寫

[root@ansible PlayBook]# cat testtmp.yml 
#模板示例
---
- hosts: all
  remote_user: root
  vars:
    - listen_port: 88    #定義變量

  tasks:
    - name: Install Httpd
      yum: name=httpd state=installed
    - name: Config Httpd
      template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf    #使用模板
      notify: Restart Httpd
    - name: Start Httpd
      service: name=httpd state=started
      
  handlers:
    - name: Restart Httpd
      service: name=httpd state=restarted

2)模板文件準備,httpd配置文件準備,這裏配置文件端口使用了變量

[root@ansible PlayBook]# cat templates/httpd.conf.j2 |grep ^Listen
Listen {{ listen_port }}

3)查看目錄結構

# 目錄結構
[root@ansible PlayBook]# tree .
.
├── templates
│   └── httpd.conf.j2
└── testtmp.yml

1 directory, 2 files

4)執行playbook,因爲192.168.1.36那臺機器是6的系統,模板文件裏面的配置文件是7上面默認的httpd配置文件,httpd版本不同(6默認版本爲2.2.15,7默認版本爲2.4.6),因此拷貝過去後啓動報錯。下面使用playbook中的判斷語句進行處理;此處先略過

[root@ansible PlayBook]# ansible-playbook testtmp.yml 

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

TASK [Gathering Facts] ******************************************************************************
ok: [192.168.1.36]
ok: [192.168.1.32]
ok: [192.168.1.33]
ok: [192.168.1.31]

TASK [Install Httpd] ********************************************************************************
ok: [192.168.1.36]
ok: [192.168.1.33]
ok: [192.168.1.32]
ok: [192.168.1.31]

TASK [Config Httpd] *********************************************************************************
changed: [192.168.1.31]
changed: [192.168.1.33]
changed: [192.168.1.32]
changed: [192.168.1.36]

TASK [Start Httpd] **********************************************************************************
fatal: [192.168.1.36]: 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"}
changed: [192.168.1.32]
changed: [192.168.1.33]
changed: [192.168.1.31]

RUNNING HANDLER [Restart Httpd] *********************************************************************
changed: [192.168.1.31]
changed: [192.168.1.32]
changed: [192.168.1.33]

PLAY RECAP ******************************************************************************************
192.168.1.31               : ok=5    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.1.32               : ok=5    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.1.33               : ok=5    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.1.36               : ok=3    changed=1    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

template之when

when語句參考

條件測試:若是須要根據變量、facts或此前任務的執行結果來作爲某task執行與否的前提時要用到條件測試,經過when語句執行,在task中使用jinja2的語法格式、
when語句:
task後添加when子句便可使用條件測試;when語句支持jinja2表達式語法。

相似這樣:

tasks:
  - command: /bin/false
    register: result
    ignore_errors: True
  - command: /bin/something
    when: result|failed
  - command: /bin/something_else
    when: result|success
  - command: /bin/still/something_else
    when: result|skipped

示例:經過when語句完善上面的httpd配置

1)準備兩個配置文件,一個centos6系統httpd配置文件,一個centos7系統httpd配置文件。

[root@ansible PlayBook]# tree templates/
templates/
├── httpd6.conf.j2     #6系統2.2.15版本httpd配置文件
└── httpd7.conf.j2     #7系統2.4.6版本httpd配置文件

0 directories, 2 files

2)修改playbook文件,經過setup模塊獲取系統版本去判斷。setup經常使用模塊

[root@ansible PlayBook]# cat testtmp.yml 
#when示例
---
- hosts: all
  remote_user: root
  vars:
    - listen_port: 88

  tasks:
    - name: Install Httpd
      yum: name=httpd state=installed
    - name: Config System6 Httpd
      template: src=httpd6.conf.j2 dest=/etc/httpd/conf/httpd.conf
      when: ansible_distribution_major_version == "6"   #判斷系統版本,爲6便執行上面的template配置6的配置文件
      notify: Restart Httpd
    - name: Config System7 Httpd
      template: src=httpd7.conf.j2 dest=/etc/httpd/conf/httpd.conf
      when: ansible_distribution_major_version == "7"   #判斷系統版本,爲7便執行上面的template配置7的配置文件
      notify: Restart Httpd
    - name: Start Httpd
      service: name=httpd state=started

  handlers:
    - name: Restart Httpd
      service: name=httpd state=restarted

3)執行playbook

[root@ansible PlayBook]# ansible-playbook testtmp.yml

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

TASK [Gathering Facts] ******************************************************************************
ok: [192.168.1.31]
ok: [192.168.1.32]
ok: [192.168.1.33]
ok: [192.168.1.36]

TASK [Install Httpd] ********************************************************************************
ok: [192.168.1.32]
ok: [192.168.1.33]
ok: [192.168.1.31]
ok: [192.168.1.36]

TASK [Config System6 Httpd] *************************************************************************
skipping: [192.168.1.33]
skipping: [192.168.1.31]
skipping: [192.168.1.32]
changed: [192.168.1.36]

TASK [Config System7 Httpd] *************************************************************************
skipping: [192.168.1.36]
changed: [192.168.1.33]
changed: [192.168.1.31]
changed: [192.168.1.32]

TASK [Start Httpd] **********************************************************************************
ok: [192.168.1.36]
ok: [192.168.1.31]
ok: [192.168.1.32]
ok: [192.168.1.33]

RUNNING HANDLER [Restart Httpd] *********************************************************************
changed: [192.168.1.33]
changed: [192.168.1.31]
changed: [192.168.1.32]
changed: [192.168.1.36]

PLAY RECAP ******************************************************************************************
192.168.1.31               : ok=5    changed=2    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.1.32               : ok=5    changed=2    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.1.33               : ok=5    changed=2    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.1.36               : ok=5    changed=2    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

template之with_items

with_items迭代,當有須要重複性執行的任務時,可使用迭代機制。
對迭代項的引用,固定變量名爲item,要在task中使用with_items給定要迭代的元素列表。
列表格式:
  字符串
  字典

示例1:經過with_items安裝多個不一樣軟件

編寫playbook

[root@ansible PlayBook]# cat testwith.yml 
# 示例with_items
---
- hosts: all
  remote_user: root

  tasks:
    - name: Install Package
      yum: name={{ item }} state=installed   #引用item獲取值
      with_items:     #定義with_items
        - httpd
        - vsftpd
        - nginx

上面tasks寫法等同於:

---
- hosts: all
  remote_user: root
  tasks:
    - name: Install Httpd
      yum: name=httpd state=installed
    - name: Install Vsftpd
      yum: name=vsftpd state=installed
    - name: Install Nginx
      yum: name=nginx state=installed

示例2:經過嵌套子變量建立用戶並加入不一樣的組

1)編寫playbook

[root@ansible PlayBook]# cat testwith01.yml 
# 示例with_items嵌套子變量
---
- hosts: all
  remote_user: root

  tasks:
    - name: Create New Group
      group: name={{ item }} state=present
      with_items: 
        - group1
        - group2
        - group3 

    - name: Create New User
      user: name={{ item.name }} group={{ item.group }} state=present
      with_items:
        - { name: 'user1', group: 'group1' } 
        - { name: 'user2', group: 'group2' } 
        - { name: 'user3', group: 'group3' }

2)執行playbook並驗證

# 執行playbook
[root@ansible PlayBook]# ansible-playbook testwith01.yml

# 驗證是否成功建立用戶及組
[root@ansible PlayBook]# ansible all -m shell -a 'tail -3 /etc/passwd'
192.168.1.36 | CHANGED | rc=0 >>
user1:x:500:500::/home/user1:/bin/bash
user2:x:501:501::/home/user2:/bin/bash
user3:x:502:502::/home/user3:/bin/bash

192.168.1.32 | CHANGED | rc=0 >>
user1:x:1001:1001::/home/user1:/bin/bash
user2:x:1002:1002::/home/user2:/bin/bash
user3:x:1003:1003::/home/user3:/bin/bash

192.168.1.31 | CHANGED | rc=0 >>
user1:x:1002:1003::/home/user1:/bin/bash
user2:x:1003:1004::/home/user2:/bin/bash
user3:x:1004:1005::/home/user3:/bin/bash

192.168.1.33 | CHANGED | rc=0 >>
user1:x:1001:1001::/home/user1:/bin/bash
user2:x:1002:1002::/home/user2:/bin/bash
user3:x:1003:1003::/home/user3:/bin/bash

template之for if

經過使用forif能夠更加靈活的生成配置文件等需求,還能夠在裏面根據各類條件進行判斷,而後生成不一樣的配置文件、或者服務器配置相關等。

示例1

1)編寫playbook

[root@ansible PlayBook]# cat testfor01.yml 
# template for 示例
---
- hosts: all
  remote_user: root
  vars:
    nginx_vhost_port:
      - 81
      - 82
      - 83

  tasks:
    - name: Templage Nginx Config
      template: src=nginx.conf.j2 dest=/tmp/nginx_test.conf

2)模板文件編寫

# 循環playbook文件中定義的變量,依次賦值給port
[root@ansible PlayBook]# cat templates/nginx.conf.j2 
{% for port in nginx_vhost_port %}
server{
     listen: {{ port }};
     server_name: localhost;
}
{% endfor %}

3)執行playbook並查看生成結果

[root@ansible PlayBook]# ansible-playbook testfor01.yml

# 去到一個節點看下生成的結果發現自動生成了三個虛擬主機
[root@linux ~]# cat /tmp/nginx_test.conf 
server{
     listen: 81;
     server_name: localhost;
}
server{
     listen: 82;
     server_name: localhost;
}
server{
     listen: 83;
     server_name: localhost;
}

示例2

1)編寫playbook

[root@ansible PlayBook]# cat testfor02.yml 
# template for 示例
---
- hosts: all
  remote_user: root
  vars:
    nginx_vhosts:
      - web1:
        listen: 8081
        server_name: "web1.example.com"
        root: "/var/www/nginx/web1"
      - web2:
        listen: 8082
        server_name: "web2.example.com"
        root: "/var/www/nginx/web2"
      - web3:
        listen: 8083
        server_name: "web3.example.com"
        root: "/var/www/nginx/web3"

  tasks:
    - name: Templage Nginx Config
      template: src=nginx.conf.j2 dest=/tmp/nginx_vhost.conf

2)模板文件編寫

[root@ansible PlayBook]# cat templates/nginx.conf.j2 
{% for vhost in nginx_vhosts %}
server{
     listen:    {{ vhost.listen }};
     server_name:    {{ vhost.server_name }};
     root:   {{ vhost.root }}; 
}
{% endfor %}

3)執行playbook並查看生成結果

[root@ansible PlayBook]# ansible-playbook testfor02.yml

# 去到一個節點看下生成的結果發現自動生成了三個虛擬主機
[root@linux ~]# cat /tmp/nginx_vhost.conf 
server{
     listen:    8081;
     server_name:    web1.example.com;
     root:   /var/www/nginx/web1; 
}
server{
     listen:    8082;
     server_name:    web2.example.com;
     root:   /var/www/nginx/web2; 
}
server{
     listen:    8083;
     server_name:    web3.example.com;
     root:   /var/www/nginx/web3; 
}

示例3

for循環中再嵌套if判斷,讓生成的配置文件更加靈活

1)編寫playbook

[root@ansible PlayBook]# cat testfor03.yml 
# template for 示例
---
- hosts: all
  remote_user: root
  vars:
    nginx_vhosts:
      - web1:
        listen: 8081
        root: "/var/www/nginx/web1"
      - web2:
        server_name: "web2.example.com"
        root: "/var/www/nginx/web2"
      - web3:
        listen: 8083
        server_name: "web3.example.com"
        root: "/var/www/nginx/web3"

  tasks:
    - name: Templage Nginx Config
      template: src=nginx.conf.j2 dest=/tmp/nginx_vhost.conf

2)模板文件編寫

# 說明:這裏添加了判斷,若是listen沒有定義的話,默認端口使用8888,若是server_name有定義,那麼生成的配置文件中才有這一項。
[root@ansible PlayBook]# cat templates/nginx.conf.j2 
{% for vhost in nginx_vhosts %}
server{
     {% if vhost.listen is defined %}
     listen:    {{ vhost.listen }};
     {% else %}
     listen: 8888;
     {% endif %}
     {% if vhost.server_name is defined %}
     server_name:    {{ vhost.server_name }};
     {% endif %}
     root:   {{ vhost.root }}; 
}
{% endfor %}

3)執行playbook並查看生成結果

[root@ansible PlayBook]# ansible-playbook testfor03.yml

# 去到一個節點看下生成的結果發現自動生成了三個虛擬主機
[root@linux ~]# cat /tmp/nginx_vhost.conf 
server{
          listen:    8081;
          root:   /var/www/nginx/web1; 
}
server{
          listen: 8888;
          server_name:    web2.example.com;
          root:   /var/www/nginx/web2; 
}
server{
          listen:    8083;
          server_name:    web3.example.com;
          root:   /var/www/nginx/web3; 
}

上面三個示例的圖片展現效果

例一

例二

例三

相關文章
相關標籤/搜索