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

猜你喜欢

转载自blog.csdn.net/marvinchen003/article/details/79890622