Ansible playbook 實例 1(template)

==========================

***  前置文章  ***

Ansible Fundamental

Ansible的安裝配置及基本用法

Ansible Playbook 實踐

==========================

Playbooks can declare configurations, but they can also orchestrate steps of any manual ordered process, even as different steps must bounce back and forth between sets of machines in particular orders. They can launch tasks synchronously or asynchronously.

下面是官網給出的一個實例:

---
- hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
  remote_user: root
  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:                                               # 這裏用到了template,在下文中有講解
      src: /srv/httpd.j2
      dest: /etc/httpd.conf
    notify:                                                 # notify和handler也是常用模塊
    - restart apache
  - name: ensure apache is running (and enable it at boot)
    service:
      name: httpd
      state: started
      enabled: yes
  handlers:
    - name: restart apache
      service:
        name: httpd
        state: restarted

Template

Ansible 使用template模塊在Jinja2中引用變量。(Jinja2:一個純Python實現的模板引擎)

舉個例子:

 - 
   name: Test Jinja2 Templating 
   hosts: localhost 
   vars: 
     array_of_numbers: 
       - 12 
       - 34 
       - 06 
       - 34 
   tasks: 
   - debug: 
       msg: 'Lowest = {{ array_of_numbers | min }}'  # {{ array_of_numbers | min }} 訪問變量值,並利用 | min filer 取出最小值

notify handler

notify

notify這個action可用於在每個play的最後被觸發,這樣可以避免多次有改變發生時每次都執行指定的操作,取而代之,僅在所有的變化發生完成後一次性地執行指定操作。在notify中列出的操作稱爲handler,也即notify中調用handler中定義的操作。

handlers

Handlers 也是一些 task 的列表,通過名字來引用,它們和一般的 task 並沒有什麼區別。Handlers 是由通知者進行 notify, 如果沒有被 notify,handlers 不會執行。不管有多少個通知者進行了 notify,等到 play 中的所有 task 執行完成之後,handlers 也只會被執行一次。Handlers 最佳的應用場景是用來重啓服務,或者觸發系統重啓操作。除此以外很少用到了。
--- name: test.yml just for test  
    hosts: testserver  
    vars:    
        region: ap-southeast-1  
    tasks:    
        - name: template configuration
          file      template: src=template.j2 dest=/etc/foo.conf      
    notify:          
        - restart memcached          
        - restart apache  
    handlers:    
          - name: restart memcached      
            service: name=memcached state=restarted    
          - name: restart apache      
            service: name=apache state=restarted

參考文檔

Ansible入門notify和handlers: https://www.linuxidc.com/Linux/2017-02/140871.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章