Ansibleのベストプラクティスを読む
最近インフラ部分を触ることが多く、特にAnsibleに触れる機会に恵まれているため、しっかりと勉強してみようと思います。 色々とモジュールには触れてみたものの、そういえばベストプラクティス的なやつにまだ目を通してなかったと思ったのが昨日。
公式リファレンスに記載されているものからいくつか気になったものを意訳して取り上げてみます。
ディレクトリ構成
例では以下のディレクトリ構成が挙げられていました。
production # inventory file for production servers
staging # inventory file for staging environment
group_vars/
group1.yml # here we assign variables to particular groups
group2.yml
host_vars/
hostname1.yml # here we assign variables to particular systems
hostname2.yml
library/ # if any custom modules, put them here (optional)
module_utils/ # if any custom module_utils to support modules, put them here (optional)
filter_plugins/ # if any custom filter plugins, put them here (optional)
site.yml # master playbook
webservers.yml # playbook for webserver tier
dbservers.yml # playbook for dbserver tier
roles/
common/ # this hierarchy represents a "role"
tasks/ #
main.yml # <-- tasks file can include smaller files if warranted
handlers/ #
main.yml # <-- handlers file
templates/ # <-- files for use with the template resource
ntp.conf.j2 # <------- templates end in .j2
files/ #
bar.txt # <-- files for use with the copy resource
foo.sh # <-- script files for use with the script resource
vars/ #
main.yml # <-- variables associated with this role
defaults/ #
main.yml # <-- default lower priority variables for this role
meta/ #
main.yml # <-- role dependencies
library/ # roles can also include custom modules
module_utils/ # roles can also include custom module_utils
lookup_plugins/ # or other types of plugins, like lookup in this case
webtier/ # same kind of structure as "common" was above, done for the webtier role
monitoring/ # ""
fooapp/ # ""
group_varsとhost_varsが切り出されているのが特徴的ですね。 拡張性を考えるとこのくらい細分化しているほうが良いのかもしれません。
別のディレクトリ構成
こちらは別バージョンの構成。
inventories/
production/
hosts # inventory file for production servers
group_vars/
group1.yml # here we assign variables to particular groups
group2.yml
host_vars/
hostname1.yml # here we assign variables to particular systems
hostname2.yml
staging/
hosts # inventory file for staging environment
group_vars/
group1.yml # here we assign variables to particular groups
group2.yml
host_vars/
stagehost1.yml # here we assign variables to particular systems
stagehost2.yml
library/
module_utils/
filter_plugins/
site.yml
webservers.yml
dbservers.yml
roles/
common/
webtier/
monitoring/
fooapp/
先程と異なるのはproductionとstagingの下にそれぞれのvarsが移動した点ですね。 本番とステージングではホストも異なることが多いでしょうからこちらのほうが個人的にはしっくりきます。
トップレベルPlaybooksのRole別分離
トップレベルのファイルではその配下のPlaybooksをインポートするのみに努める。 今回の例ではsite.ymlが最上位でwebservers.ymlとdbservers.ymlが二番手に当たる。 下記のようにsite.ymlは二番手のymlをincludeするのみ、二番手のymlはそのtargethostとrolesを管理するのみ。
handerの活用
handerファイルにはtaskがchengesの結果になった場合のみ実行するtaskを配置する? ここはあまりピンと来ませんでした。taskの役割で格納するディレクトリを分けろということなのか?
必要な部分のみ実行する
基本的には全体実行をやり直すのではなく、tag付けなどを利用して部分的に実行できるように管理する。
まとめ
いくつかピックアップしてご紹介しました。 基本は普通のプログラミングと同じく、「名前を付けてグルーピングしろ」に尽きるかと思います。 複数のディストリビューションへのプロビジョニングを想定する場合など、少しの仕様の差が大きな問題につながる可能性もあるため、うまく使いこなしていきたいところ。