自動メンテナンスツールAnsibleのPlaybooksループ文


ansibleを使用して自動化されたメンテナンスを行う場合は、いくつかのユーザーを追加したり、いくつかのMySQLユーザーを作成したり、権限を付与したり、ディレクトリの下のすべてのファイルを操作したりするなど、いくつかの操作を繰り返すことが避けられません.幸いplaybooksはループ文をサポートしており、いくつかのニーズを簡単に規範的に実現することができます.
with_itemsはplaybooksで最も基本的で最もよく使われるループ文です.
- name: add several users
  user: name={{ item }} state=present groups=wheel
  with_items:
     - testuser1
     - testuser2

上記の例では、2人のユーザを追加するのはそれぞれtestuser 1,testuser 2である.
ユーザー・リストを変数に事前に割り当て、ループ・ステートメントで呼び出すこともできます.
with_items: "{{ somelist }}"
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' }

ネストされたループ
- name: give users access to multiple databases
  mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
  with_nested:
    - [ 'alice', 'bob' ]
    - [ 'clientdb', 'employeedb', 'providerdb' ]

item[0]は、ループの最初のリストの値['alice','bob']である.item[1]は、2番目のリストの値です.aliceとbobの2人のユーザーをループして作成し、3つのデータベースにすべての権限を付与することを示します.
ユーザー・リストを変数に事前に割り当てることもできます.
- name: here, 'users' contains the above list of employees
  mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
  with_nested:
    - "{{users}}"
    - [ 'clientdb', 'employeedb', 'providerdb' ]

with_dictは、より複雑なデータ構造を巡回することができます.
たとえば、次の変数があります.
---
users:
  alice:
    name: Alice Appleworth
    telephone: 123-456-7890
  bob:
    name: Bob Bananarama
    telephone: 987-654-3210

各ユーザーのユーザー名と携帯電話番号を出力する必要があります
tasks:
  - name: Print phone records
    debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
    with_dict: "{{ users }}"

ファイルマッチングパスwith_fileglob1つのディレクトリのすべてのファイルに一致
---
- hosts: all

  tasks:

    # first ensure our target directory exists
    - file: dest=/etc/fooapp state=directory

    # copy each file over that matches the given pattern
    - copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
      with_fileglob:
        - /playbooks/files/fooapp/*

注意:ロールでは、with_fileglobを相対パスで使用し、ansibleはrole/<rolename>/filesにパスを解析します.
データの並列集合の遍歴
[root@web1 ~]# cat /etc/ansible/loop.yml
---
- hosts: webservers
  remote_user: root
  vars:
    alpha: [ 'a','b','c','d']
    numbers: [ 1,2,3,4 ]
  tasks:
    - debug: msg="{{ item.0 }} and {{ item.1 }}"
      with_together:
         - "{{ alpha }}"
         - "{{ numbers }}"

[root@web1 ~]# ansible-playbook /etc/ansible/loop.yml

PLAY [webservers] ************************************************************* 

GATHERING FACTS *************************************************************** 
ok: [192.168.1.65]

TASK: [debug msg="{{ item.0 }} and {{ item.1 }}"] ***************************** 
ok: [192.168.1.65] => (item=['a', 1]) => {
    "item": [
        "a", 
        1
    ], 
    "msg": "a and 1"
}
ok: [192.168.1.65] => (item=['b', 2]) => {
    "item": [
        "b", 
        2
    ], 
    "msg": "b and 2"
}
ok: [192.168.1.65] => (item=['c', 3]) => {
    "item": [
        "c", 
        3
    ], 
    "msg": "c and 3"
}
ok: [192.168.1.65] => (item=['d', 4]) => {
    "item": [
        "d", 
        4
    ], 
    "msg": "d and 4"
}

PLAY RECAP ******************************************************************** 
192.168.1.65               : ok=2    changed=0    unreachable=0    failed=0

サブエレメントの遍歴
ユーザー・リストを巡回し、各ユーザーを作成し、各ユーザーに特定のSSHキーでログインするように構成する必要がある場合.変数ファイルの内容は次のとおりです.
---
users:
  - name: alice
    authorized:
      - /tmp/alice/onekey.pub
      - /tmp/alice/twokey.pub
    mysql:
        password: mysql-password
        hosts:
          - "%"
          - "127.0.0.1"
          - "::1"
          - "localhost"
        privs:
          - "*.*:SELECT"
          - "DB1.*:ALL"
  - name: bob
    authorized:
      - /tmp/bob/id_rsa.pub
    mysql:
        password: other-mysql-password
        hosts:
          - "db1"
        privs:
          - "*.*:SELECT"
          - "DB2.*:ALL"

Playbooksでは次のように定義されています.
- user: name={{ item.name }} state=present generate_ssh_key=yes
  with_items: "{{users}}"

- authorized_key: "user={{ item.0.name }} key='{{ lookup('file', item.1) }}'"
  with_subelements:
     - users
     - authorized

ネストされたサブリストを巡回することもできます.
- name: Setup MySQL users
  mysql_user: name={{ item.0.user }} password={{ item.0.mysql.password }} host={{ item.1 }} priv={{ item.0.mysql.privs | join('/') }}
  with_subelements:
    - users
    - mysql.hosts

循環整数シーケンスwith_sequenceは、開始値と終了値を指定したり、成長ステップを指定したりする自己増加整数シーケンスを生成します.
パラメータはkey=valueで指定され、formatで出力のフォーマットが指定されます.
数字は10進数、16進数、8進数です.
---
- hosts: all

  tasks:

    # create groups
    - group: name=evens state=present
    - group: name=odds state=present

    # create some test users
    - user: name={{ item }} state=present groups=evens
      with_sequence: start=0 end=32 format=testuser%02x

    # create a series of directories with even numbers for some reason
    - file: dest=/var/stuff/{{ item }} state=directory
      with_sequence: start=4 end=16 stride=2

    # a simpler way to use the sequence plugin
    # create 4 groups
    - group: name=group{{ item }} state=present
      with_sequence: count=4

ランダム選択with_random_choiceリストからランダムに値を取得できます.
- debug: msg={{ item }}
  with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

Do-Untilサイクル
- action: shell /usr/bin/foo
  register: result
  until: result.stdout.find("all systems go") != -1
  retries: 5
  delay: 10

上記の例ではshellモジュールを繰り返し実行し、shellモジュールが実行するコマンド出力内容に「all systems go」が含まれている場合に実行を停止します.再試行5回、遅延時間10秒.retriesデフォルトは3、delayデフォルトは5です.
タスクの戻り値は、最後のループの戻り結果です.
循環登録変数
ループでregisterを使用する場合、索保存の結果にはresultsキーワードが含まれ、このキーワード保存モジュールが実行した結果のリスト
- shell: echo "{{ item }}"
  with_items:
    - one
    - two
  register: echo

変数echoの内容は次のとおりです.
{
    "changed": true,
    "msg": "All items completed",
    "results": [
        {
            "changed": true,
            "cmd": "echo \"one\" ",
            "delta": "0:00:00.003110",
            "end": "2013-12-19 12:00:05.187153",
            "invocation": {
                "module_args": "echo \"one\"",
                "module_name": "shell"
            },
            "item": "one",
            "rc": 0,
            "start": "2013-12-19 12:00:05.184043",
            "stderr": "",
            "stdout": "one"
        },
        {
            "changed": true,
            "cmd": "echo \"two\" ",
            "delta": "0:00:00.002920",
            "end": "2013-12-19 12:00:05.245502",
            "invocation": {
                "module_args": "echo \"two\"",
                "module_name": "shell"
            },
            "item": "two",
            "rc": 0,
            "start": "2013-12-19 12:00:05.242582",
            "stderr": "",
            "stdout": "two"
        }
    ]
}

登録変数を巡回した結果:
- name: Fail if return code is not 0
  fail:
    msg: "The command ({{ item.cmd }}) did not have a 0 return code"
  when: item.rc != 0
  with_items: "{{echo.results}}"

例:
[root@web1 ~]# cat /etc/ansible/reloop.yml
---
- hosts: webservers
  remote_user: root
  tasks:
   - shell: echo "{{ item }}"
     with_items:
      - one
      - two
     register: echo
   - debug: msg="{{ echo }}"
   - name: Fail if return code is not 0
     fail: msg=" The command {{ item.cmd }} has a 0 return code"
     when: item.rc != 0
     with_items: "{{ echo.results }}"


[root@web1 ~]# ansible-playbook /etc/ansible/reloop.yml

PLAY [webservers] ************************************************************* 

GATHERING FACTS *************************************************************** 
ok: [192.168.1.65]

TASK: [shell echo "{{ item }}"] *********************************************** 
changed: [192.168.1.65] => (item=one)
changed: [192.168.1.65] => (item=two)

TASK: [debug msg="{{ echo }}"] ************************************************ 
ok: [192.168.1.65] => {
    "msg": "{'msg': 'All items completed', 'changed': True, 'results': [{u'stdout': u'one', u'changed': True, u'end': u'2015-08-05 11:30:42.560652', u'start': u'2015-08-05 11:30:42.549056', u'cmd': u'echo \"one\"', u'rc': 0, 'item': 'one', u'stderr': u'', u'delta': u'0:00:00.011596', 'invocation': {'module_name': u'shell', 'module_args': u'echo \"one\"'}, 'stdout_lines': [u'one'], u'warnings': []}, {u'stdout': u'two', u'changed': True, u'end': u'2015-08-05 11:30:44.105387', u'start': u'2015-08-05 11:30:44.093500', u'cmd': u'echo \"two\"', u'rc': 0, 'item': 'two', u'stderr': u'', u'delta': u'0:00:00.011887', 'invocation': {'module_name': u'shell', 'module_args': u'echo \"two\"'}, 'stdout_lines': [u'two'], u'warnings': []}]}"
}

TASK: [Fail if return code is not 0] ****************************************** 
skipping: [192.168.1.65] => (item={u'cmd': u'echo "one"', u'end': u'2015-08-05 11:30:42.560652', u'stderr': u'', u'stdout': u'one', u'changed': True, u'rc': 0, 'item': 'one', u'warnings': [], u'delta': u'0:00:00.011596', 'invocation': {'module_name': u'shell', 'module_args': u'echo "one"'}, 'stdout_lines': [u'one'], u'start': u'2015-08-05 11:30:42.549056'})
skipping: [192.168.1.65] => (item={u'cmd': u'echo "two"', u'end': u'2015-08-05 11:30:44.105387', u'stderr': u'', u'stdout': u'two', u'changed': True, u'rc': 0, 'item': 'two', u'warnings': [], u'delta': u'0:00:00.011887', 'invocation': {'module_name': u'shell', 'module_args': u'echo "two"'}, 'stdout_lines': [u'two'], u'start': u'2015-08-05 11:30:44.093500'})

PLAY RECAP ******************************************************************** 
192.168.1.65               : ok=4    changed=1    unreachable=0    failed=0