8
3

More than 1 year has passed since last update.

【Ansible】複数のタスクをループさせる処理

Posted at

はじめに

Ansibleでループ(loopやwith_itemsなど)を使用する場合、ループは各タスクごとに記載する必要がある。そのため以下の図のように複数タスクを1つにまとめ、①→②→③→②→③→④の順番に処理を行いたい場合は工夫が必要。

image.png

環境

Ansible: 2.14.1
Python: 3.10.6

失敗①

無理だろうなと思いつつ各タスクごとにwith_itemsを記載。
当然ながら、①→②→②→③→③→④の順番で実行される。
playbook.yaml

tasks:
  - name: task1
   debug:
      msg: "start"
 
  - name: task2
      debug:
      msg: "good morning {{ item }}"
    with_items:
      - taro
      - jiro

  - name: task3
    debug:
      msg: "hello {{ item }}"
    with_items:
      - taro
      - jiro

  - name: task4
    debug:
      msg: "finish"

出力結果
image.png

失敗②

タスク②とタスク③をblockで囲ってみたがエラーが出た。

playbook.yaml

tasks:
  - name: task1
   debug:
      msg: "start"

  - name: task2_and_task3
    block: 
      - name: task2
        debug:
          msg: "good morning {{ item }}"

      - name: task3
        debug:
          msg: "hello {{ item }}"
    with_items:
      - taro
      - jiro
  
  - name: task4
   debug:
      msg: "finish"

出力結果
image.png
loopでも同様のエラー
image.png

調べたところ、blockでまとめたタスクをループさせることはできないらしい。

解決策

ループさせたいタスクを別のplaybookに記載し、include_tasksで呼び出すことで解決。

playbook.yaml

tasks:
  - name: task1
    debug:
      msg: "good morning"
  
  - name: task2_and_task3
    include_tasks: task2_and_task3.yaml
    with_items:
      - taro
      - jiro

  - name: task4
    debug:
      msg: "finish"

task2_and_task3.yaml

- name: task2
  debug: "good morning {{ item }}"

- name: task3
  debug: "hello {{ item }}"

実行結果
実行結果を見ると、①→②→③→②→③→④の順番で処理されていることが分かる。
image.png

8
3
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
8
3