問題
突然ですが、問題です。
以下のようにタグのついた Playbook、role があるとします。
- tag_playbook.yml
- hosts: localhost gather_facts: no roles: - role: testrole tags: - tag_parent
- roles/testrole/tasks/main.yml
- name: task1 debug: msg: "task1" tags: - tag_parent - tag_child1 - name: task2 debug: msg: "task2" tags: - tag_child2
ansible-plabook
コマンドで-t tag_parent
を指定して Playbook を実行した場合
$ ansible-playbook -i localhost, tag_playbook.yml -t tag_parent
どのタスクが実行されるでしょうか。
答えはこちら
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
↓
答え
答えは、task1
と task2
です。(本記事のタイトル通りの挙動です)
- 実行ログ
$ ansible-playbook -i localhost, tag_playbook.yml -t tag_parent PLAY [localhost] ************************************************************************ TASK [testrole : task1] ***************************************************************** ok: [localhost] => { "msg": "task1" } TASK [testrole : task2] ***************************************************************** ok: [localhost] => { "msg": "task2" } PLAY RECAP ****************************************************************************** localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
解説
tag_playbook.yml
では、role を呼び出す指定に、タグ tag_parent
を付けています。この場合、呼ばれたロールの 各タスク にもタグ tag_parent
が付きます。継承されるようなイメージです。
そのため、呼ばれた role の タスク task2
自身には、タグ tag_parent
は付いていなくても実行される結果となります。
https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html#tag-inheritance
Adding tags: to a play, or to statically imported tasks and roles, adds those tags to all of the contained tasks. This is referred to as tag inheritance.
タスクへのタグの付き方は、ansible-playbook
コマンドの --list-tasks
オプションを利用することで確認できます。
$ ansible-playbook -i localhost, tag_playbook.yml --list-tasks playbook: tag_playbook.yml play #1 (localhost): localhost TAGS: [] tasks: testrole : task1 TAGS: [tag_child1, tag_parent] testrole : task2 TAGS: [tag_child2, tag_parent]
上記結果により、role 呼び出し側のタグ tag_parent
が継承されて task2
にもつくことが確認できます。
なお、task1
のみの実行を意図して、ansible-playbook
コマンドに -t tag_parent
を指定するのであれば、ロール呼び出し側 では tag_parent
を指定しないのが正しいです。
まとめ
タグの挙動はうっかり忘れがちなものもあると思いますので、たまに公式ドキュメントを見返すのが良さそうです。
※role や import* ではなく、include* のよう動的読み込みの場合は継承されないようです。
Tag inheritance is not applicable to dynamic inclusions such as include_role and include_tasks.
- 検証環境
- Ansible 2.9.0
参考
[2021/03/24 追記]