LoginSignup
1
1

More than 5 years have passed since last update.

Ansible でなんちゃってテンプレートヒエラルキー。template と with_first_found の組み合わせをテストした。

Posted at

テンプレートヒエラルキーを作ってテストしてみた

  • 1プロジェクトファイルで環境毎にinventoryを分けている
  • グループ毎に同じファイルをコピーしたり、テンプレートでの配布をする。
  • たまにホスト固有のファイルに変えるかも
  • まぁ具体的には /etc/hosts ファイルとかw(みなまでいうな
  • template ファイル自体に処理を押し込んでj2のお世話になりたくなかっただけ。見通し悪くなるし
  • 他にもっといいやり方があったら教えて欲しい
  • こんだけコード掲載するなら大人しくgithubにあげたほうがいいかもしれない
  • とはいえ bitbucket のプライベートリポジトリで書いてるから面倒なんだよ。。w

inventory

inventory/local


[ifg_local]
web
mng
db
[web]
host1
[mng]
host2
[db]
host3

inventory/stg


[ifg_stg]
web
mng
db
[web]
stg_host1
[mng]
stg_host2
[db]
stg_host3
  • 前の記事にも書いたけど、ansible.cfg で inventory ファイルを切り替えて使っている

playbook

  • 次の hosts role を読んで(include)るだけ(省略)

roles/hosts/tasks/main.yml


- name: hosts | copy to /etc/hosts
  # template: src={{ item }} dest=/etc/hosts group=root owner=root mode=0644
  # debug で見たほうがわかりやすいかも
  debug:
  with_first_found:
    - files:
        - hosts.{{ inventory_hostname }}.j2
        - hosts.{{ ansible_hostname }}.j2
        - hosts.{{ group_names[3] | default('x') }}.j2
        - hosts.{{ group_names[2] | default('x') }}.j2
        - hosts.{{ group_names[1] | default('x') }}.j2
        - hosts.{{ group_names[0] | default('x') }}.j2
        - hosts.j2
      paths:
        - ../templates/

roles/hosts/templates/

優先度高い順


hosts.host1.j2   # host1固有(inventory_hostname)
hosts.web.j2     # web グループ固有(ansible_hostname)
hosts.ifg_stg.j2 # ifg_stg グループ固有(group_names)
hosts.j2         # ifg_localのweb以外

hosts.x.j2 を作らないこと。default() の中を変えたらなんでもいいけど。

たぶん

  • 実際には ifg_XX ってつけた一番大きいグループレベル(inventory毎≒環境毎)でファイルを作って、hosts.j2 は使わない
  • inventory_hostnameで固有を作るのがメイン
  • どうしても必要になったら、with_first_found に hosts.{{ group_names[x] }}.{{ inventory_hostname }}.j2 は作ると、使い勝手があがるかもしれない

本当は

  • with_first_found の中で一発で一番大きい所属グループ名(例でいえば ifg_XX)を取得したかったんだけど、うまくいかなかった
  • j2 template 内でなら出来るのは知ってる
  • 前記事の空ループと一緒でかっこ悪いのは認識してるw
1
1
0

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
1