【事象】
AnsibleのDry Runテストの際、いつもサービスのstart時や、symlinkを張るtaskで、not found等のエラーになりroleが最後まで確認できず困っていた。CIツールも結局Dry Runで流してるコマンドは同じ。。。
# ansible-playbook -i hosts playbook.yml -vvv --check
【解決】
tasksにwhen: not ansible_check_mode
と入れることで、コケそうなtaskもskipしてくれる。
いざ...
■YAMLの書きっぷり
[root@localhost work]# cat test/tasks/01_test_check.yml
# Check status of taks
- name: Check status of test
systemd:
state: started
enabled: yes
name: "{{ test.name }}"
when: not ansible_check_mode ←これを書く
[root@localhost work]#
■スキップしてくれたログ
TASK [Test : Check status of test]
********************************************************************************************************************
task path: /work/test/tasks/01_test_checkl.yml:9
skipping: [test1] => {
"changed": false,
"skip_reason": "Conditional result was False" ←skipしてくれてい〜る!!
}
【備考】
ドキュメント通りにcheck_mode: no
で実施してみたけれど、真っ赤っ赤になって叱られます。
どうやら、check_mode: no
だとDry Runでもとりあえず強制的に実行しちゃうみたいですね~。
そのため、インストーラがない、ファイルが無い等の場合は false が返ってきてコケるのですね。
tasks:
- name: this task will make changes to the system even in check mode
command: /something/to/run --even-in-check-mode
check_mode: no
- name: this task will always run under checkmode and not change the system
lineinfile:
line: "important config"
dest: /path/to/myconfig.conf
state: present
check_mode: yes
>Enabling or disabling check mode for tasks
https://docs.ansible.com/ansible/latest/user_guide/playbooks_checkmode.html#id2
<参考>
Skip Ansible task when running in check mode?
https://stackoverflow.com/questions/28729567/skip-ansible-task-when-running-in-check-mode
ansible_check_mode
https://docs.ansible.com/ansible/2.5/user_guide/playbooks_variables.html?highlight=ansible_check_mode