2014/04/03

ansible ループ 条件分岐

・単純ループ:
  name: add several users
 user: name={{ item }} state=present groups=wheel
 with_items:
    - testuser1
    - testuser2


・with_items + 辞書によるループ
 name: add several users
 user: name={{ item.name }} state=present groups={{ item.groups }}
 with_items:
   - { name: 'testuser1', groups: 'wheel' }
   - { name: 'testuser2', groups: 'root' }


・コマンド実行結果を with_items で回すーー>かなり動的に
- name: retrieve the list of home directories
   command: ls /home
   register: home_dirs

 - name: add home dirs to the backup spooler
   file: path=/mnt/bkspool/{{ item }} src=/home/{{ item }} state=link
   with_items: home_dirs.stdout_lines
   # same as with_items: home_dirs.stdout.split()
  
  
・with_sequence による整数範囲ループ(Pythonの range のようなもの)
  file: dest=/var/stuff/{{ item }} state=directory
  with_sequence: start=4 end=16 stride=2
  
  
・do-until(+sleep)ループ
 action: shell /usr/bin/foo
 register: result
 until: result.stdout.find("all systems go") != -1
 retries: 5
 delay: 10
 ★★action: shell /usr/bin/foo 
 ==>適切に変換してくれるみたいな。。


・ファイルglobでループ
 copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
 with_fileglob:
   - /playbooks/files/fooapp/*
==>with_fileglob matches all files in a single directory, non-recursively, that match a pattern


・単純な変数による分岐
 - name: "shutdown Debian flavored systems"
   command: /sbin/shutdown -t now
   when: ansible_os_family == "Debian"
  
・コマンド実行結果による分岐
 tasks:
   # まずはコマンドを実行してresultに格納
   - shell: /usr/bin/foo
     register: result
     ignore_errors: True

   # タスクが失敗した場合
   - debug: msg="it failed"
     when: result|failed

   # タスクにより更新された場合
   - debug: msg="it changed"
     when: result|changed

   # タスクが成功した場合
   - debug: msg="it succeeded"
     when: result|success

   # タスクがskipされた場合
   - debug: msg="it was skipped"
     when: result|skipped

   # タスクの標準出力によって分岐
   - shell: echo "hi does not found"
     when: result.stdout.find('hi') != -1

・複数ターゲットが関連するタスクを実行する(Rolling Update)
 - hosts: webservers
   serial: 5

   tasks:
     - name: take out of load balancer pool
       local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}

     - name: actual steps would go here
       yum: name=acme-web-stack state=latest

     - name: add back to load balancer pool
       local_action: command: /usr/bin/add_back_to_pool {{ inventory_hostname }}

local_action モジュールはplaybookを実行しているホストで実行するコマンドを定義する。上記の例だとWEBサーバを5並列でLB切り離し→更新→LB組み込みを実行する。