役割を拡張する
基本的な役割構造ができたので、典型的なAnsible役割のさらに多くのコンポーネントを含めて拡張しましょう。変数、ハンドラ、テンプレートを追加します。
まず、デフォルト変数を追加しましょう。defaults
ディレクトリに main.yml
ファイルを作成します。
nano defaults/main.yml
以下のコンテンツを追加します。
---
example_variable: "This is a default value"
これは example_variable
のデフォルト値を設定し、役割を使用する際に上書きできます。
次に、ハンドラを作成します。handlers
ディレクトリに main.yml
ファイルを作成します。
nano handlers/main.yml
以下のコンテンツを追加します。
---
- name: Restart example service
debug:
msg: "This would restart a service in a real scenario"
実際のシナリオでは、このハンドラはサービスを再起動する場合がありますが、この例ではメッセージを表示するだけです。
次に、テンプレートを作成します。templates
ディレクトリに example_template.j2
という名前のファイルを作成します。
nano templates/example_template.j2
以下のコンテンツを追加します。
This is an example template.
The value of example_variable is: {{ example_variable }}
このテンプレートは、Jinja2構文を使用して example_variable
の値を含めています。
最後に、新しいコンポーネントを使用するように tasks/main.yml
を更新しましょう。
nano tasks/main.yml
既存のコンテンツを以下のものに置き換えます。
---
- name: Print a message
debug:
msg: "This is a task from our example role!"
- name: Use our variable
debug:
msg: "The value of example_variable is: {{ example_variable }}"
- name: Create a file from our template
template:
src: example_template.j2
dest: /tmp/example_file.txt
notify: Restart example service
この更新されたタスクリストは、現在、変数を使用し、テンプレートからファイルを作成し、ハンドラに通知しています。