test プラグイン
test プラグインは template 式を評価し、True または False を返します。test プラグインを使用すると、conditionals を作成して、タスク、ブロック、プレイ、Playbook、およびロールのロジックを実装できます。Ansible は Jinja の一部として同梱される standard tests `_ を使用し、特殊な tesst プラグインを追加します。:ref:`create custom Ansible test plugins <developing_test_plugins> が可能です。
test プラグインの有効化
カスタムの test プラグインを追加するには、そのプラグインを、ロール内のプレイの隣りにある test_plugins ディレクトリーに置くか、ansible.cfg で設定したディレクトリーソースの 1 つに置きます。
test プラグインの使用
テストは、Ansible でテンプレートを使用できる場所で使用できます。これはプレイ、変数ファイル、または template モジュールの Jinja2 テンプレートで使用できます。test プラグインの使用の詳細は、テスト を参照してください。
テストは常に True または False を返し、ブール型です。別の戻り型が必要な場合には、フィルターを確認する必要があります。
test プラグインは、テンプレートの is ステートメントを使用して認識できます。また、フィルターの select ファミリーの一部として使用することもできます。
vars:
is_ready: '{{ task_result is success }}'
tasks:
- name: conditionals are always in 'template' context
action: dostuff
when: task_result is failed
テストには常に _input があり、これは通常 is の左側にあります。テストは、ほとんどのプログラミング関数と同様に追加のパラメーターを取ることもできます。これらのパラメーターは positional (key=value ペアとして渡される) または named (key=value ペアとして渡される) のいずれかになります。両方のタイプを渡す場合は、位置引数を最初に指定する必要があります。。
tasks:
- name: pass positional parameter to match test
action: dostuff
when: myurl is match("https://example.com/users/.*/resources")
- name: pass named parameter to truthy test
action: dostuff
when: myvariable is truthy(convert_bool=True)
- name: pass both types to 'version' test
action: dostuff
when: sample_semver_var is version('2.0.0-rc.1+build.123', 'lt', version_type='semver')
リストと test プラグインの使用
As mentioned above, one way to use tests is with the select family of filters (select, reject, selectattr, rejectattr).
# give me only defined variables from a list of variables, using 'defined' test
good_vars: "{{ all_vars|select('defined') }}"
# this uses the 'equalto' test to filter out non 'fixed' type of addresses from a list
only_fixed_addresses: "{{ all_addresses|selectattr('type', 'equalsto', 'fixed') }}"
# this does the opposite of the previous one
only_fixed_addresses: "{{ all_addresses|rejectattr('type', 'equalsto', 'fixed') }}"
プラグイン一覧
ansible-doc -t filter -l を使用して、利用可能なプラグインの一覧を表示します。ansible-doc -t filter <plugin name> を使用して、特定のドキュメントと例を参照してください。
参考
- Ansible Playbook
Playbook の概要
- テスト
テストの使用
- 条件分岐 (Conditional)
条件分岐文の使用
- filter プラグイン
filter プラグイン
- テスト
テストの使用
- lookup プラグイン
lookup プラグイン
- User Mailing List
ご質問はございますか。Google Group をご覧ください。
- リアルタイムチャット
Ansible チャットチャンネルへの参加方法