LoginSignup
38
34

More than 5 years have passed since last update.

【Ansible】with_itemsループまとめ

Posted at

はじめに

AnsibleにはPlaybookの中でループを使うことにより、タスクを繰り返し実行することができます。
その中で一番良く使うであろうwith_itemsのループ処理をご紹介致します!

共通のルール

  • タスクからループ内の要素を使用する際はitemという名前の変数を用いる

with_items

単純にリストでループしたい場合に使う

- name: ディレクトリの作成
  file: path=/root/{{ item }} state=directory
  with_items:
    - test1
    - test2
    - test3

アイテムにはディクショナリを使用することも可能

- name: ディレクトリの作成
  file: path=/root/{{ item.name }} state=directory owner={{ item.user }} group={{ item.group }}
  with_items:
    - { name: test1, user: test1, group: test }
    - { name: test2, user: test2, group: test }
    - { name: test3, user: test3, group: test } 

リストのリストは1階層まで展開される

- debug:
    msg: "{{ item }}"
  with_items:
    - [ a, b, c ]
    - [ 4, 5, 6 ]

上記の場合、[ a, b, c, 4, 5, 6 ]という一つのリストをループさせた際と同じ挙動となる

複数のリストをまとめてループさせる

- vars:
    - staging: [ test1, test2, test3 ]
    - production: [ test4, test5, test6 ]

- name: ディレクトの作成
  file: path={{ item }} state=directory
  with_items:
    - "{{ staging }}"
    - "{{ production }}"

おわりに

with系のループ処理は色々あるので使い分けをうまくすれば効率的なPlaybookが書けそうですね!

38
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
34