7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ansible で他のホストの一覧を参照する

Posted at

Ansible で他のグループに属するホスト一覧を参照する方法のメモ。

モチベーション

検証のために一時的に使用する次のような小規模なシステムを Ansible で構成管理したかった。

  • 1台のリバースプロキシサーバと複数のHTTPサーバで構成される。
  • HTTPサーバの台数は可変。
  • Inventory File に記載したHTTPサーバのリストから、リバースプロキシサーバで使用する設定ファイルを生成したい。

結論

Magic Variablesgroups を使用する。

groups は Inventory のグループがキー、ホストのリストが値になった辞書になている。

詳細

Ansible にはマジック変数 (Magic Variables) という自動で設定される変数があり、これを使うことでホストの情報を参照することができる。

試しに次のような Inventory File と Playbook を書いて確認してみた。

hosts
[proxy]
127.0.0.1

[backend]
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5

Inventory File にはリバースプロキシサーバ用のグループ proxy と、HTTPサーバ用のグループ backend の2つのグループを定義した。

site.yml
---
- hosts: proxy
  tasks:
    - name: dump hosts in backend group
      template:
        src: "{{ inventory_dir }}/config.txt.j2"
        dest: "{{ inventory_dir }}/config.txt"

設定ファイルに見立てたテンプレートを用意し、グループ backend に属するすべてのホスト名が出力されるようにする。

config.txt.js
{% for host in groups['backend'] %}
- {{ host }}
{% endfor %}

実行してみる。

$ ansible-playbook -i hosts site.yml
...
$ cat list.txt
- 192.168.1.1
- 192.168.1.2
- 192.168.1.3
- 192.168.1.4
- 192.168.1.5

きちんとホスト名が出力されている。

これでHTTPサーバが増減しても Inventory File を書き換えで対応できる。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?