playbook 实例

vim ~/.vimrc

autocmd FileType yaml setlocal sw=2 ts=2 et ai

变量使用及错误处理

---
- hosts: db
  remote_user: root
  vars:
    user: 'dd'
    pwd: 'aa'
  tasks:
    - name: add user
      user:
        name: "{{ user }}"
        password: "{{ '{{pwd}}' | password_hash('sha512')}}"
    - name: set account valid date
      shell: chage -d 0 "{{ user }}"
ignore_errors: true # 忽略错误

 

安装apache

---
- hosts: web
  remote_user: root
  tasks:
    - name: install the latest version of Apache
      yum:                                                       
        name: httpd
        state: latest
    - lineinfile:
        path: /etc/httpd/conf/httpd.conf
        regexp: '^Listen '
        insertafter: '^#Listen '
        line: 'Listen 8080'
    - lineinfile:
        path: /etc/httpd/conf/httpd.conf
        regexp: '^#ServerName'
        line: 'ServerName localhost'
    - copy:
        src: index.html
        dest: /var/www/html/index.html
        owner: apache
        group: apache
        mode: 0644
    - service:
        name: httpd
        state: started
        enabled: yes

 

when 条件判断

---
- hosts: web
  remote_user: root
  tasks:
    - shell: uptime | awk '{printf("%.2f", $(NF-2))}'
      register: result                           
    - service:
        name: httpd
        state: stopped
      when: result.stdout|float > 0.7

 

handlers 触发

---
- hosts: cache
  remote_user: root
  tasks:
    - copy:
        src: /root/httpd.conf
        dest:  /etc/httpd/conf/httpd.conf
        owner: root
        group: root
        mode: 0644
      notify:
        - restart httpd
  handlers:
     - name: restart httpd
       service: name=httpd state=restarted

 

withe_item 循环

---
- hosts: cache
  remote_user: root
  tasks:
    - user:
        name: "{{item.name}}"
        group: "{{item.group}}"
        password: "{{item.pwd|password_hash('sha512')}}"
      with_items:
        - 
          name: a1
          pwd: aa
          group: users
        - 
          name: a2
          pwd: bb
          group: wheel
        - 
          name: a3
          pwd: cc
          group: root

 

posted @ 2019-02-22 17:08  Ray_chen  阅读(252)  评论(0编辑  收藏  举报