はじめに
ansibleのtemplateモジュールのドキュメントを見ると、
Templates are processed by the Jinja2 templating language (http://jinja.pocoo.org/docs/) - documentation on the template formatting can be found in the Template Designer Documentation (http://jinja.pocoo.org/docs/templates/).
と記載があり、Jinja2というテンプレート記法が使えることがわかります。
ansibleのtemplateモジュールはこれまでも使っていたけど、Jinja2のテンプレート記法、中でも、テンプレート継承を使ってみたら、実際いろいろ捗ったので、ここで紹介したいと思います。
Example Playbook
記法についての詳細は、Template Inheritance - Jinja2 Documentationの説明を見ていただいた上で、AnsibleのPlaybookに当てはめると下記のようになります。
やっていること
-
テンプレートからファイルを生成(ローカル)
base.j2を継承したextended.j2を元に、ファイルを生成(extended.txt) -
ファイルをコピー(リモート)
ファイル構成
├── inventory_example
├── roles
│ └── example
│ ├── files
│ │ └── extended.txt
│ ├── tasks
│ │ └── create_file.yml
│ │ └── copy_file.j2
│ └── templates
│ ├── base.j2
│ └── extended.j2
inventory
-
inventory_example
- hosts: localhost tasks: - include: roles/example/tasks/create_file.yml - hosts: remote_host tasks: - include: roles/example/tasks/copy_file.yml
tasks
-
roles/example/tasks/create_file.yml
- name: Create file from template template: src=extended.j2 dest=roles/example/files/extended.txt -
roles/example/tasks/copy_file.yml
- name: Copy file to remote host copy: src=extended.txt dest={{ path_to_root }}/extended.txt
templates
-
roles/example/templates/base.j2
This is default contents. {% block additional_contents %}{% endblock %} -
roles/example/templates/extended.j2
{% extends "roles/example/templates/base.j2" %} {% block additional_contents %} This is additional contents. {% endblock %}
files
-
roles/example/files/extended.txt
This is default contents. This is additional contents.
おわりに
普段からphpのTwigというテンプレートを使っていて、Jinjaを見たときに、「Twigとそっくり!」と思ったら、TwigのREADMEに、
Twig uses a syntax similar to the Django and Jinja template languages which inspired the Twig runtime environment.
ときっちり書いてありました。
Jinja inspiredなテンプレートエンジンは他にもNunjucksなど、複数の言語で実装されているようです。