LoginSignup
10
10

More than 5 years have passed since last update.

Ansibleで環境毎の変数を定義する

Posted at

こういう系のツールではお馴染みの dev, prod, stageなどの環境を分けるような機能はAnsibleにはないが、実現は簡単にできる。

Group Variablesを利用する

一番スマートなのがGroup Variablesで定義する方法。
ツリーはこんな感じ。

.
├── dbservers.yml
├── development.ini
├── group_vars
│   ├── all.yml
│   ├── dbservers.yml
│   ├── development.yml
│   ├── production.yml
│   └── webservers.yml
├── production.ini
├── site.yml
└── webservers.yml

group_varsにproduction.iniとdevelopment.iniに対応したようなファイルが設置されていて、一見すると読み込んだInventoryファイル名がそのまま使われているように思えるが、実際はそうではない。

各Inventoryファイルで架空のグループ(development, production)を定義し、このような動作を実現している。

development.ini
[webservers]
192.168.1.10

[dbservers]
192.168.1.20

[development:children]
webservers
dbservers
production.ini
[webservers]
172.16.1.10
172.16.1.11

[dbservers]
172.16.1.20
172.16.1.21

[production:children]
webservers
dbservers

Inventoryで変数を定義する。

Inventory内で直接webservers:varsなどとやるほうがお手軽感がある。
しかし、Inventory - Ansible Documentasionでは次のように書かれている。

The preferred practice in Ansible is actually not to store variables in the main inventory file.

Dynamic Inventoryは別として、たしかにInventoryファイルではdictの扱いもできないため、YAMLでの定義ができたほうが望ましいと思う。

10
10
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
10
10