1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ansible Tips: shellモジュールで冪等性に対応し、正しいchanged結果を持たせ、かつdry runに対応させる例

Last updated at Posted at 2024-06-03

備忘

Shellモジュールにて、changedおよびdry runに対応させるロジック例

上のstderrを用いる方法例の更新およびdry run対応。
shellモジュール内で実行される処理をまとめることで、可読性を向上。

---
- hosts: all
  gather_facts: false
  vars:
    shell_execution_guard: |-
      [ $? -eq 0 ] && exit 0  # If check succeeds, exit without changes
      echo "__changed__" >&2  # Indicate that changes are needed
      {{ "exit 0" if ansible_check_mode }}  # In check mode, exit without making changes

  tasks:

    - name: システム変更を伴うかどうか内部で確認するコマンド例
      check_mode: false
      ansible.builtin.shell: |-
        # 確認コマンド
        test -f ./test.txt

        {{ shell_execution_guard }}

        # 変更コマンド
        touch ./test.txt
      register: r
      changed_when: '"__changed__" in r.stderr_lines'

  • 確認コマンドはシステムへの変更を行わないコマンドとする。

    • その戻り値($?)が0の場合、変更コマンドは実行せずchanged: falseとする。
    • その戻り値($?)が0以外の場合、変更コマンドを実行しchanged: trueとする。
  • dry run(ansible-playbook --check)の場合、

    • 確認コマンドは、check_mode: falseにより実行し、変更処理が行われる筈かどうか判断
    • 変更コマンドは、shell_execution_guardの最後に付与した{{ ' exit 0;' if ansible_check_mode }}により実行させない。
  • shell_execution_guard

    • ここでは複数のshellモジュールでの利用を考慮してplay varsとしているが、shell:内に直書きでも、task varsでも、set_factによる固定でもご自由に。
  • changedかどうかのshellモジュールへの連携は、ここではstderrに決め打ちした特定の文字列__changed__を書き出すことで実装。

1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?